Set A Root View Controller Programmatically in Swift 5

iOS Swift

Sometimes, you would want to set the root view controller programmatically without using a storyboard in swift.

In this short tutorial, you’re going to learn how to do that with step by steps instructions.

Let’s get started!

STEP #1: Get Rid of Storyboard

  • Go ahead and create a project in Xcode.
  • Then, go to the Project NavigatorMain.Storyboard file and
  • Hit delete key and choose Remove Reference to get rid of it…Yep, you heard it right 🙂

STEP #2: Get Rid of Storyboard References

Now, let’s get rid of the two instances that point to the Main. storyboard file.

1. Go to Project Navigator → top-level project folder → General Tab → Deployment Info section → clear the text Main from the input field, which is next to the Main Interface label, like in the image below

2. Go to the Project Navigator → info.plist file → Application Scene Manifest property → Scene Configurationitem 0 and get rid of the property Storyboard Name by clicking the icon that has a minus in the circle next to it.

► Run the app and you will see the black screen and let’s change that by setting a new root view controller.

STEP #3 Set A Root View Controller

Open up SceneDelegate.swift file from the Project Navigator and replace the existing code to the willConnectTo() method:

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {    
    guard let winScene = (scene as? UIWindowScene) else { return }
    window = UIWindow(windowScene: winScene)
    window?.rootViewController = ViewController()
    window?.makeKeyAndVisible()
}

First, instantiate a new UIWindow object passing UIWindowScene as a parameter in the constructor.

And, make sure that the ViewController() which is assigned to the window’s rootViewController matches with the file name ViewController.Swift

One more thing I want to do before running the app is to add a background color to the ViewController() class so that I can make sure that it’s working properly.

Go to ViewController.swift class file→ viewDidLoad() method.

Add the following code to that method,

view.backgroundColor = .systemRed

If everything goes well, you should be able to see the background color similar to the screenshot above when you run the app.

There you have it and now the app is running with a root view controller that is set programmatically without a storyboard.