Swift - 无法转换类型' UITabBarController'

时间:2015-12-06 16:53:59

标签: ios swift uitabbarcontroller

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

当我触发segue时,它会显示以下错误:

  

无法转换类型' UITabBarController' (0x10d414030)来   ' 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;

        }
    }

知道如何克服这个问题吗?

1 个答案:

答案 0 :(得分:9)

由于您的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