简体   繁体   English

更改根视图控制器

[英]Change root View Controller

I have a problem with changing root in my app. 我在应用程序中更改root时遇到问题。

在此处输入图片说明

Design of my app. 我的应用程序的设计。 After I login into app I would like to change root vc to UITabBarViewController to clean a stack. 登录应用程序后,我想将root vc更改为UITabBarViewController来清理堆栈。

I've faced multiple problems. 我遇到了多个问题。

  1. Setting vc to tab bar on apply login action -> or in bottom vc: 将vc设置为应用登录操作->或底部vc中的选项卡栏:

     self.performSegue(withIdentifier: "goToMainTabBar", sender: nil) override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let vc = segue.destination as? TabBarViewController { UIApplication.shared.keyWindow?.rootViewController = vc } } 

The app going to crash with: 该应用程序将崩溃:

Application tried to present modal view controller on itself. Presenting controller is TabBarViewController
  1. Next problem is if we set a root in TabBarViewController viewDidLoaded . 下一个问题是,如果我们在TabBarViewController viewDidLoaded设置一个根。

    UIApplication.shared.keyWindow?.rootViewController = self

Tab bar items embaded in UINavigationController doesnt have Navigation controller in it selfs, so the nav vc is not instantiated ? 嵌入在UINavigationController选项卡栏项自身没有导航控制器,因此不会实例化Nav vc吗? Becouse wheenver I will enter into item vc child -> I can't back any more. 因为我将进入项目vc child->我再也不能支持了。 If i won;t change a root vc there everything is fine. 如果我不更改根vc,那一切都很好。

For 1) you can't present a view controller using a segue and then use it to replace the root view controller in the prepare. 对于1),您不能使用segue呈现视图控制器,然后使用它来替换prepare中的根视图控制器。 You will need to instantiate the tab view controller from the storyboard and then replace the root view controller. 您将需要从情节提要中实例化选项卡视图控制器,然后替换根视图控制器。

Something like this: 像这样:

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "TabController")
UIApplication.shared.keyWindow?.rootViewController = vc

(assuming the storyboard is called 'Main' and you give the tab controller the storyboard ID of 'TabController'. (假设情节提要被称为“主要”,并且您为标签页控制器提供了情节提要ID“ TabController”。

I'm not quite clear on what the issue is for 2. 对于2的问题,我不太清楚。

However as a general note I would approach this differently and instead of having the login controller as your initial view controller have the tab bar as the initial controller and then just present the login controller the first time the app starts. 但是,作为一般性注释,我将采取不同的方法,而不是使用登录控制器作为您的初始视图控制器,而使用标签栏作为初始控制器,然后在应用程序首次启动时仅显示登录控制器。 That way you avoid replacing the root controller at all and it's all more controlled. 这样一来,您就可以避免完全替换根控制器,并且可以更好地控制根控制器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM