[英]Change root view controller of AppDelegate cause an exception of UIViewControllerHierarchyInconsistency
Outside the AppDelegate
, I want to change the rootViewController
of it. 在
AppDelegate
之外,我想更改它的rootViewController
。 In other words, I want to put a new navigation controller on top of what I had before in my window and then push the new controller in this navigation controller: 换句话说,我想在窗口中放置一个新的导航控制器,然后将其推入该导航控制器中:
func JumpToPage(_ controller: UIViewController) {
guard let rootController = AppDelegate.shared?.presentationViewController else {
return
}
let navigationController = UINavigationController(rootViewController: rootController)
navigationController.pushViewController(controller, animated: true)
AppDelegate.shared?.window?.rootViewController = navigationController
}
}
But this function cause the app to crash with the following error message: 但是此功能导致应用程序崩溃并显示以下错误消息:
Terminating app due to uncaught exception 'UIViewControllerHierarchyInconsistency',
reason: 'adding a root view controller <MyExampleController> as a child of view controller:<UINavigationController>'
How should I solve it? 我应该如何解决?
Change from 从
let navigationController = UINavigationController(rootViewController: rootController)
To 至
let navigationController = UINavigationController(rootViewController: controller)
Update 更新
func JumpToPage(_ controller: UIViewController) {
guard let rootController = AppDelegate.shared?.presentationViewController else {
return
}
let navigationController = UINavigationController(rootViewController: controller)
AppDelegate.shared?.window?.rootViewController = navigationController
}
Instead of trying to replace navigation controller, I'm replacing root VC in the initial navigation controller as follows. 我没有尝试替换导航控制器,而是在初始导航控制器中替换了根VC,如下所示。
In AppDelegate: 在AppDelegate中:
func application(_ application: UIApplication, didFinishLaunchingWithOptions ...) {
let storyboard = UIStoryboard(name: "FirstVC", bundle: Bundle.main)
let firstViewController = instantiateInitialViewController()! as! FirstViewController
navigationController = UINavigationController(rootViewController: firstViewController)
window = UIWindow(frame: UIScreen.main.bounds)
window!.rootViewController = navigationController
window!.makeKeyAndVisible()
return true
}
Then, I change root VC w/in FirstViewController as follows: 然后,我在FirstViewController中更改根VC,如下所示:
func someFuncInFirstVC() {
let allControllers = NSMutableArray(array: self.navigationController!.viewControllers)
allControllers.removeObject(at: allControllers.count - 1) // remove root VC, count should be one...
let secondViewController = SecondViewController()
allControllers.add(secondViewController as AnyObject) // this becomes new root VC since nav stack is empty now
navigationController!.setViewControllers(allControllers as [AnyObject] as! [UIViewController], animated: true)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.