ios - 更改 rootviewcontroller 后快速导航 Controller 返回 nil

标签 ios swift swift3 uinavigationcontroller

我正在尝试更改我的应用程序的 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。谁能解释我在流程中的错误是什么?

enter image description here

最佳答案

答案很简单,只需像这样将“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/

相关文章:

swift - Swift 中的稍后日期

iOS 导航栏在向后滑动时按下返回后变得困惑

camera - ios 10 对未渲染的 View 进行快照会生成空快照

iphone - shell脚本中的xcode构建版本号

ios - NSMutableDictionary initWithContentsOfFile 中的内存泄漏

ios - Xcode:添加一个在出现静态分析器警告或错误时失败的测试?

swift - 你能在 Swift 中评估一个字符串吗?

ios - 无法在 opengl es 2.0 中加载多个纹理

swift - 以编程方式 UISlider 不改变宽度

swift - 我想循环遍历集群注释中的所有注释