Set Window’s Root View Controller in Swift

With this Swift code example, I am going to share with you how to set the current window’s root view controller to a different one.

The effect is as if you are replacing the current view controller with a new one. The new view controller will not be pushed into the navigation stack and it will not be presented on top of the window. It will take place of the existing view controller and it very much looks like you are replacing the current view controller with a new one. I use this approach whenever I need to log the user out and take them to page #1.

The below code example needs to be run from a ViewController rather than from AppDelegate.swift file for example.

Setting the Window’s Root View Controller Code Example in Swift

 //declare variable in appdelegate 
var window: UIWindow?

//Write below code in SceneDelegate.swift 's willConnectTo method 
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.window = self.window

//Write below code in ViewController 
let signInPage = self.storyboard?.instantiateViewController(withIdentifier: "ViewController") as! ViewController
let appDelegate = UIApplication.shared.delegate
appDelegate?.window??.rootViewController = signInPage

 


Leave a Reply

Your email address will not be published. Required fields are marked *