问题
I have a login screen that takes credentials, and based on outcome of verification, user is redirected to another view controller or not. The login view controller is controlled by NavigationController and once the login is successful, user is redirected to a Home view controller controlled by UITabBarController
.
When I trigger the segue, it says the following error:
Could not cast value of type 'UITabBarController' (0x10d414030) to 'Mawq.HomeViewController' (0x10a7ed220).
Here is the code for the segue:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if (segue.identifier == "showHomeFromLoginSegue") {
/*Provide ServiceToken a value from API*/
// pass data to next view
let destinationVC = segue.destinationViewController as! HomeViewController
destinationVC.userObject = self.userObject;
}
}
Any idea how to overcome this issue?
回答1:
Since your segue is connected to a UITabBarController
, you need to cast it to UITabBarController
and get the ViewController object using the viewControllers
property of the tab bar controller.
let tabCtrl = segue.destinationViewController as! UITabBarController
let destinationVC = tabCtrl.viewControllers![0] as! HomeViewController // Assuming home view controller is in the first tab, else update the array index
destinationVC.userObject = self.userObject;
For Swift 4:
let tabCtrl: UITabBarController = segue.destination as! UITabBarController
let destinationVC = tabCtrl.viewControllers![0] as! HomeViewController
destinationVC.userObject = userObject[String!] // In case you are using an array or something else in the object
来源:https://stackoverflow.com/questions/34120068/swift-could-not-cast-value-of-type-uitabbarcontroller