在AppDelegate
之外,我想更改它的rootViewController
。换句话说,我想在窗口中放置一个新的导航控制器,然后将其推入该导航控制器中:
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
}
}
但是此功能导致应用程序崩溃并显示以下错误消息:
Terminating app due to uncaught exception 'UIViewControllerHierarchyInconsistency',
reason: 'adding a root view controller <MyExampleController> as a child of view controller:<UINavigationController>'
我应该如何解决?
答案 0 :(得分:0)
从
更改let navigationController = UINavigationController(rootViewController: rootController)
收件人
let navigationController = UINavigationController(rootViewController: controller)
更新
func JumpToPage(_ controller: UIViewController) {
guard let rootController = AppDelegate.shared?.presentationViewController else {
return
}
let navigationController = UINavigationController(rootViewController: controller)
AppDelegate.shared?.window?.rootViewController = navigationController
}
答案 1 :(得分:0)
我没有尝试替换导航控制器,而是按如下方式替换了初始导航控制器中的根VC。
在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
}
然后,我在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)
}