首页 > 解决方案 > 如何快速更改 rootViewController?

问题描述

我正在开发一个没有登录注销功能的应用程序。当用户打开应用程序时,他会看到主屏幕。现在在设置页面中有一个名为 Pin Lock 应用程序的选项。当用户选择此选项时,会出现 PinScreen(如 OTP 屏幕),然后用户设置 Pin。之后,当用户关闭应用程序时,首先会出现 Pin 锁定屏幕,要求用户输入 pin。那么我该怎么做呢?

if UserDefaults.standard.bool(forKey: "LoggedIn") == false {

        let story = UIStoryboard(name: "Main", bundle:nil)
        let vc = story.instantiateViewController(withIdentifier: "EnterPin") as! UINavigationController
        UIApplication.shared.windows.first?.rootViewController = vc
        UIApplication.shared.windows.first?.makeKeyAndVisible()

        let enterPinViewController = self.storyboard.instantiateViewController(identifier: "EnterPinViewController") as! EnterPinViewController
        self.navigationController.present(enterPinViewController, animated: true, completion: nil)

    } else if UserDefaults.standard.bool(forKey: "LoggedIn") == true {

        let story = UIStoryboard(name: "Main", bundle:nil)
        let vc = story.instantiateViewController(withIdentifier: "MainController") as! UINavigationController
        UIApplication.shared.windows.first?.rootViewController = vc
        UIApplication.shared.windows.first?.makeKeyAndVisible()

        let mainViewController = self.storyboard.instantiateViewController(identifier: "ViewController") as! ViewController
        self.navigationController.present(mainViewController, animated: true, completion: nil)


    }

目前我将 UserDefaults 值设置为 true 和 false,并将 Pin 保存在 UserDefaults 本身中。我曾尝试更改 rootViewController 但没有发生任何事情,这意味着每次主屏幕出现而不是 Pin Screen 时。

标签: swiftuinavigationcontroller

解决方案


let viewController = MainViewController()

guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
   return
 }
    
guard let window = appDelegate.window else {
   return
}
    
window.rootViewController = viewController

推荐阅读