且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 iOS 项目中控制多个导航控制器

更新时间:2023-02-13 07:51:59

在某些时候,我会假设应用程序能够确定用户是否登录,基于您必须设置所需的应用的根视图控制器.

At some point, I would assume that the app is able to determine whether the user loggedin or not, based on that you have to set the desired root view controller for the app.

对于这种情况,***的地方是application(_:didFinishLaunchingWithOptions:) AppDelegate 文件中的方法:

For such a case, the best place to do that is application(_:didFinishLaunchingWithOptions:) method in the AppDelegate file:

告诉代理启动过程即将完成,应用程序几乎可以运行了.

Tells the delegate that the launch process is almost done and the app is almost ready to run.

为简单起见,假设您将 isLoggedin 布尔值保存在 UserDefault 中,因此可以这样实现:

For simplicity, let's say that you are saving isLoggedin boolean in the UserDefault, so it could be achieved like this:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // the flag for determining whether the user loggedin or not
    let isLoggedin = UserDefaults.standard.bool(forKey: "K_isLoggedin")

    // the desired initial view controller (based on the value of `isLoggedin`)
    let initialViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: isLoggedin ? "TabbarIdentifier" : "FirstNavigationIdentifier")

    // setting the app rootViewController
    window?.rootViewController = initialViewController

    return true
}

请注意,TabbarIdentifier"代表故事板中的标签栏控制器,FirstNavigationIdentifier"代表故事板中的第一个导航视图控制器.

Note that "TabbarIdentifier" represents the tabbar controller at the storyboard and also "FirstNavigationIdentifier" represents the first navigation view controller at the storyboard.

如果您不知道如何设置视图控制器标识符,请查看这个答案应该会有所帮助.

if you are unaware of how to set the view controller identifier, checking this answer should help.

从技术上讲,设置所需的根视图控制器意味着设置rootViewController 到应用程序的主 window (AppDelegate窗口).

Technically speaking, setting the desired root view controller means setting the rootViewController to the main window of the app (AppDelegate window).