Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a new root view controller

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.

enter image description here

like image 712
user2722667 Avatar asked Oct 27 '15 17:10

user2722667


People also ask

How do I get root view controller?

The root view controller is simply the view controller that sits at the bottom of the navigation stack. You can access the navigation controller's array of view controllers through its viewControllers property. To access the root view controller, we ask for the first item of the array of view controllers.

What is root view controller in Swift?

The root view controller provides the content view of the window. Assigning a view controller to this property (either programmatically or using Interface Builder) installs the view controller's view as the content view of the window.


2 Answers

Swift 4.2

May be you should try this

let mainStoryBoard = UIStoryboard(name: "Main", bundle: nil) let redViewController = mainStoryBoard.instantiateViewController(withIdentifier: "respectiveIdentifier") as! ViewController let appDelegate = UIApplication.shared.delegate as! AppDelegate appDelegate.window?.rootViewController = redViewController 
like image 149
Vashum Avatar answered Sep 26 '22 01:09

Vashum


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() 
like image 45
Sandeep Maurya Avatar answered Sep 25 '22 01:09

Sandeep Maurya