How to switch root view controllers in Swift

Here’s how to switch root view controllers in Swift. It comes in handy when you want to instantiate a view controller from your storyboard and display it at arbitrary points in your app.

Imagine a single view application with an additional view controller. Each view controller has a button that switches to the other view controller. To make it more interesting, each view controller is embedded in a navigation controller. The methods to switch to either view controller are called centrally in the AppDelegate.swift file:

func switchViewControllers() {
    
    // switch root view controllers
    let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
    let nav = storyboard.instantiateViewControllerWithIdentifier("Two")
    
    self.window?.rootViewController = nav
    
}

func switchBack() {
    
    // switch back to view controller 1
    let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
    let nav = storyboard.instantiateViewControllerWithIdentifier("One")
    
    self.window?.rootViewController = nav
}

In our storyboard, let’s make sure that each navigation controller has a Storyboard ID for manual instantiation. In the above example that’s One and Two respectively.

To call the first method from our first view controller, we’ll do this:

@IBAction func switchButtonPresed(sender: AnyObject) {
    
    // switch root view controllers in AppDelegate
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    appDelegate.switchViewControllers()
}

We’ll grab a reference to our UIApplication’s delegate and typecast it to be an instance of AppDelegate. Unlike in Objective-C, there’s no need to import this class into our view controller in Swift. Then we go ahead and call the method.

In our second view controller, we’ll do exactly the same, except for calling the other method in AppDelegate:

@IBAction func switchButtonPressed(sender: AnyObject) {
    
    // change to first view controller
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    appDelegate.switchBack()
}

Here’s a demo project that shows the above in action:





One thought on “How to switch root view controllers in Swift

Leave a Reply