我在我的故事板中添加了一个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时,代码正常工作。我做错了什么?
编辑: 我绕过导航控制器并将seque直接放到ViewController上。它现在有效!
答案 0 :(得分:0)
好,工作
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
}