Swift - 无法转换类型 'UITabBarController' 的值

Swift - Could not cast value of type 'UITabBarController'

我有一个需要凭据的登录屏幕,根据验证结果,用户是否被重定向到另一个视图控制器。登录视图控制器由 NavigationController 控制,一旦登录成功,用户将被重定向到由 UITabBarController 控制的主页视图控制器。

当我触发 segue 时,出现以下错误:

Could not cast value of type 'UITabBarController' (0x10d414030) to 'Mawq.HomeViewController' (0x10a7ed220).

这里是 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;

        }
    }

知道如何解决这个问题吗?

由于您的 segue 连接到 UITabBarController,您需要将其转换为 UITabBarController 并使用 viewControllers 属性 获取 ViewController 对象标签栏控制器。

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