Swift - Could not cast value of type 'UITabBarController'

主宰稳场 提交于 2019-12-12 10:05:10

问题


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

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