Could not cast value of type 'UITableViewController' to 'UINavigationController'

試著忘記壹切 提交于 2019-12-07 19:54:49

问题


I'm trying to segue from one view controller to another, and pass data to the next controller. But I keep getting this error:

Could not cast value of type 'UITableViewController' to 'UINavigationController' 

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {

   if (segue.identifier == "segueLogWaterData") {            
        // pass data to next view
        let nav = segue.destinationViewController as! UINavigationController
        let segueViewController = nav.topViewController as! WaterDataViewController 
    }
}

This happens with WaterDataViewController as a UITableViewController. I've also tried embedding WaterDataViewController into a UINavigationController but I get a similar error:

Could not cast value of type 'UITableViewController' to 'MyApp.WaterDataViewController'

What am I doing wrong?


回答1:


Actually, the segue.destinationViewController isn't the navigation controller; rather, it is the view controller that the segue is opening. Since UITableViewController is a subclass of UIViewController, this code should work just fine:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
    if (segue.identifier == "segueLogWaterData") {
        let dest = segue.destinationViewController as! WaterDataViewController
        //Assign to dest's properties
    }
}



回答2:


nav.topViewController is a UITableViewController. Apparently, WaterDataViewController is not a subclass of UITableViewController.

Do you mean to be using rootViewController instead?



来源:https://stackoverflow.com/questions/31213661/could-not-cast-value-of-type-uitableviewcontroller-to-uinavigationcontroller

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!