Programmatically set the initial view controller using Storyboards


What are Storyboards in Swift?

In Swift, the Storyboard is a tool that provides you with a user interface to design the UIs of your application. It provides you with a visual representation of all the screens and the connections between them. You can connect all the layout components in your controller classes easily using Storyboard.

What is instantiateViewController(withIdentifier:)?

You can set the initial view controller programmatically using the instantiateViewController(withIdentifier:) method of the UIStoryboard class.

This method takes an identifier string as a parameter, which should match the storyboard ID of the view controller you want to set as the initial view controller.

Example

Here's an example of how you might use this method to set the initial view controller in a storyboard named "Main" −

import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
    
   var window: UIWindow?
    
   func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
      // creating UIStoryboard object and initial view controller.
      let storyboard = UIStoryboard(name: "Main", bundle: nil)
      let initialController = storyboard.instantiateViewController(withIdentifier: "TestController")
        
      self.window = UIWindow(frame: UIScreen.main.bounds)
      self.window?.rootViewController = initialController
      self.window?.makeKeyAndVisible()
      return true
    }
}

In the usual scenario, we will do the setup in AppDelegate's method to set the initial controller −

Make sure the storyboard ID you are using is set in the Identity Inspector for the view controller you want to set as the initial view controller.

Conclusion

Xcode enables you to set the initial view controller using Storyboard also. You can check the initial controller which you want. But you can set the initial view controller programmatically. To do this, you can write some code in the AppDelegate’s function i.e. didFinishLaunchingWithOptions(). This method has called the first time when you open the app.

In this method, you can use the instantiateViewController(withIdentifier:) method of the UIStoryboard class to create an object of desired view controller which is designed on Storyboard. After that, you can set this object as the root view controller to the window object.

It is important to note that, when you initiate a view controller from Storyboard, you have to pass the correct storyboard ID

Updated on: 28-Feb-2023

961 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements