【问题标题】:Cannot assign value of type 'UIViewController' to type 'UITabBarController?'无法将“UIViewController”类型的值分配给“UITabBarController”类型?
【发布时间】:2016-03-17 06:48:43
【问题描述】:

我正在尝试从标识符实例化 UITabBarController,但遇到以下错误:

Cannot assign value of type 'UIViewController' to type 'UITabBarController'

这是有问题的代码:

if NSUserDefaults.standardUserDefaults().boolForKey("LoginPage") == true
    {
        tabBarController = k_Storyboard.instantiateViewControllerWithIdentifier("TabbarController")  //------Error Showed in this Line.
        self.window!.rootViewController = tabBarController
        UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.whiteColor()], forState: .Selected)
        UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor(red: 246 / 255.0, green: 206 / 255.0, blue: 206 / 255.0, alpha: 1.0)], forState: .Normal)
        isFirstPage = true
    }

【问题讨论】:

  • 有什么错误请发帖。

标签: swift compiler-errors type-safety


【解决方案1】:

答案:您正在尝试从类型 UIViewController 到子类 UITabBarController 的隐式向下转换。编译器阻止您这样做是正确的。您必须明确地通过更改来尝试强制向下转型

k_Storyboard.instantiateViewControllerWithIdentifier("TabbarController")

到以下:

k_Storyboard.instantiateViewControllerWithIdentifier("TabbarController") as! UITabBarController

如果你仍然不理解错误,请这样想:编译器无法保证从instantiateViewControllerWithIdentifier 返回的UIViewControllerUITabBarController。您必须明确保证。

【讨论】:

  • 是的,我理解并感谢 Clear My Doubt @Vatsal Manot。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-30
  • 2019-12-03
  • 2017-08-07
  • 2021-03-08
相关资源
最近更新 更多