我正在尝试更改我的应用程序的 rootViewController,它运行良好。但是,在更改 rootViewController 之后,我的 navigationController 返回 nil。因此,即使我推送任何新 Controller self.navigationController.pushViewController 的简单代码也无法正常工作。
在此之前,我想解释一下为什么我要更改我的 rootViewController。我有登录页面(这是初始 View Controller ),成功登录后用户将被重定向到 UITabBarController(3 个选项卡)。现在我想将 rootViewController 更改为这个 UITabBarController,我使用以下代码成功完成了。
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let destVC = self.storyboard?.instantiateViewController(withIdentifier: "home_view")
let rootViewController = appDelegate.window?.rootViewController as! UINavigationController
appDelegate.window?.rootViewController = destVC
现在,在更改 rootViewController 之后,我的所有 3 个选项卡及其各自的 View Controller 都可以正常工作。但是在我的一个 View Controller 中,我有一个按钮,单击该按钮后,我想将新 Controller 推送给用户。现在我面临着 nil 返回导航 View Controller 的问题。
let destVC = self.storyboard?.instantiateViewController(withIdentifier: "menu_items_view") as! MenuItems
self.navigationController?.pushViewController(destVC, animated: true)
当我使用上面的简单代码时,什么也没有发生。我所能调试的就是我的 self.navigationController 返回 nil。谁能解释我在流程中的错误是什么?
最佳答案
答案很简单,只需像这样将“destVC”放入 UINavigationController 中:
从 iOS 13 开始,keyWindow 已被弃用,我们需要编写一些代码来获取它,我在 UIApplication 上进行了扩展以获取 keyWindow
extension UIApplication {
static var key: UIWindow? {
if #available(iOS 13, *) {
return UIApplication.shared.windows.first { $0.isKeyWindow }
} else {
return UIApplication.shared.keyWindow
}
}
}
用法:
let rootViewController = UINavigationController(rootViewController: destVC)
UIApplication.key?.rootViewController = rootViewController
上一个答案
let rootViewController = UINavigationController(rootViewController: destVC)
UIApplication.shared.keyWindow?.rootViewController = rootViewController
关于ios - 更改 rootviewcontroller 后快速导航 Controller 返回 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44245089/