Swift ios set a new root view controller

前端 未结 20 813
醉话见心
醉话见心 2020-12-13 04:46

I wonder if its possible to set a new root VC?

My app gets init with a uinavigation controller that has a table view to be the root VC.

Then from the table v

相关标签:
20条回答
  • 2020-12-13 05:11

    Swift 4, 5, 5.1

        let story = UIStoryboard(name: "Main", bundle:nil)
        let vc = story.instantiateViewController(withIdentifier: "NewViewController") as! NewViewController
        UIApplication.shared.windows.first?.rootViewController = vc
        UIApplication.shared.windows.first?.makeKeyAndVisible()
    
    0 讨论(0)
  • 2020-12-13 05:14

    I wonder if its possible to set a new root VC?

    Yes, it's possible. How you do it depends on the context...

    My app gets init with a uinavigation controller that has a table view to be the root VC.

    There are actually two things that are commonly called the "root view controller":

    • UIWindow has a rootViewController property, which is writeable.

    • UINavigationController has no rootViewController property, but it does have an initializer called -initWithRootViewController:. You can set the nav controller's "root" view controller by setting it's viewControllers property.

    It sounds like you're trying to change the window's root view controller, but the code you show only changes the nav controller's viewControllers property. Try setting the window's rootViewController property directly. Understand, however, that if you take that approach then the navigation controller will go away too. If you want to keep the nav controller, on the other hand, go with your current approach.

    But I cannot get it to work. So is it possible to make the red vc in the picture act as the new root VC.

    More information here would be helpful. What do you mean by "cannot get it to work"? What happens, and what do you expect to happen?

    0 讨论(0)
提交回复
热议问题