【问题标题】:Can not cast tabBarController.viewController to UINavigationController无法将 tabBarController.viewController 转换为 UINavigationController
【发布时间】:2018-01-18 20:58:52
【问题描述】:

我在我的故事板中添加了一个 UITabBarController,当我在我的 Appdelegate 中加载 managedContext 时,我想将它传递给我的初始 ViewController。但我不能将 viewControllers 转换为 UINavigationControllers,因此 managedContext 不会加载。

这是我的代码:

 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let controller = storyboard.instantiateViewController(withIdentifier: "TabBarVC")
        self.window?.rootViewController = controller



        guard let tabBarController = window?.rootViewController as? UITabBarController else {
            print("1")
            return true
        }
        guard let navController = tabBarController.viewControllers![0] as? UINavigationController else {
            print("2")
            return true
        }
        guard let viewController = navController.topViewController as? ViewController else {

               print("3")

                return true

        }

//  Version that works for UINavigationController
//        guard let navController = window?.rootViewController as? UINavigationController,
//            let viewController = navController.topViewController as? ViewController else {
//                return true
//        }


        viewController.managedContext = coreDataStack.managedContext
        // Override point for customization after application launch.
        return true
    }

当我简单地使用 UINavigationController 时,代码可以正常工作。我做错了什么?

编辑: 我绕过了导航控制器,将序列直接放到了 ViewController 中。现在可以了!

【问题讨论】:

  • 我试图重现但不能。您确定将UITabBarController 的第一个视图控制器嵌入到故事板中的UINavigationController 中吗?
  • 谢谢,我绕过了导航控制器,直接把序列放到了ViewController中。
  • 对,所以ViewController 没有嵌入到UINavigationController 中。如果你真的想使用UINavigationController,你可以将ViewController嵌入UINavigationController,你的原始代码就可以工作了。

标签: swift core-data uinavigationcontroller uitabbarcontroller appdelegate


【解决方案1】:

很好,工作

if let tabbarcontroller = segue.destination as? UITabBarController
{
    let navigationController = tabbarcontroller.viewControllers![0] as! UINavigationController
    let controller = navigationController.topViewController as! HomeController
    controller.account = sender as? Account
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 2021-09-29
    • 1970-01-01
    • 2017-12-25
    • 2017-03-02
    • 2015-08-17
    • 2018-11-02
    相关资源
    最近更新 更多