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 view I am running another segue to a login window (present modally) If you then login you end up in the red VC/account page. What I want to do now is to set the red VC to be the new root VC of the app, and remove all underlying VC's. So that I can show a menu button/icon instead of a "Back" button
I have found this but I dont understand how to use it:
let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
let yourViewController: ViewController = storyboard.instantiateViewControllerWithIdentifier("respectiveIdentifier") as! ViewController
let navigationController = self.window?.rootViewController as! UINavigationController
navigationController.setViewControllers([yourViewController], animated: true)
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.
Swift 4, 5, 5.1
You can try out this code
In order to get the code snippet from the original question to work, I had to make a change to the third line
I am using this code in an @IBAction in the view controller that precedes the new root view controller.
Using the original code, I was receiving an error saying that my view controller had no member called
window
. After looking at the documentation, I could find no property namedwindow
. I'm wondering if the original block of code above was intended to be used inside aUINavigationController
file.Here is the block in its entirety.
Swift 4
May be you should try this
Yes, it's possible. How you do it depends on the context...
There are actually two things that are commonly called the "root view controller":
UIWindow
has arootViewController
property, which is writeable.UINavigationController
has norootViewController
property, but it does have an initializer called-initWithRootViewController:
. You can set the nav controller's "root" view controller by setting it'sviewControllers
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'srootViewController
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.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?