iOS development
Storyboards
initial view controller
Swift programming
mobile app development

Programmatically set the initial view controller using Storyboards

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

In iOS development, Storyboards provide a visual canvas for designing and structuring your application's user interface (UI). However, there may be scenarios where you need to programmatically set the initial view controller of your application rather than relying solely on the storyboard setup. This flexibility can be crucial for applications that require dynamic UI setups, such as personalized user experiences or feature-based navigation.

Understanding Storyboards

Storyboards are XML files in Xcode that allow developers to design app interfaces visually. A storyboard includes scenes (each represented by a UIViewController) and the transitions between them called segues.

In a typical storyboard setup, you define a scene as the initial view controller by checking the “Is Initial View Controller” option in the Attributes Inspector. However, there are cases where setting this programmatically is beneficial.

Reasons to Set the Initial View Controller Programmatically

  • Conditional Navigation: When the initial view depends on conditions, such as whether a user is logged in.
  • Feature Flags: For applications with feature toggles where launching a specific view depends on which features are enabled.
  • Testing and Development: During development, it can be useful to start at different view controllers quickly.
  • Modular Design: In larger apps with multiple entry points.

Programmatic Setup in AppDelegate

The AppDelegate’s application(_:didFinishLaunchingWithOptions:) method is the typical location for setting the initial view controller programmatically. Here is a step-by-step approach:

  1. Remove the Initial View Controller from the Storyboard: Start by deselecting the "Is Initial View Controller" option in your storyboard.
  2. Access the Storyboard: Load your storyboard from the main bundle.
swift
    let storyboard = UIStoryboard(name: "Main", bundle: .main)
  1. Instantiate the Initial View Controller: Choose the appropriate view controller based on your logic.
swift
1    var initialViewController: UIViewController
2    
3    if userIsLoggedIn {
4        initialViewController = storyboard.instantiateViewController(withIdentifier: "HomeViewController")
5    } else {
6        initialViewController = storyboard.instantiateViewController(withIdentifier: "LoginViewController")
7    }
  1. Set the Window's Root View Controller:
swift
    window = UIWindow(frame: UIScreen.main.bounds)
    window?.rootViewController = initialViewController
    window?.makeKeyAndVisible()

The above code assesses whether a user is logged in and sets the HomeViewController or LoginViewController accordingly. This logic is encapsulated within the application(_:didFinishLaunchingWithOptions:) method.

Example Code

Below is a complete example demonstrating setting the initial view controller programmatically in AppDelegate:

swift
1import UIKit
2
3@UIApplicationMain
4class AppDelegate: UIResponder, UIApplicationDelegate {
5
6    var window: UIWindow?
7    
8    func application(_ application: UIApplication,
9                     didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
10        
11        // Load storyboard
12        let storyboard = UIStoryboard(name: "Main", bundle: .main)
13        
14        // Determine initial view controller
15        var initialViewController: UIViewController
16        
17        // Example logic for choosing initial VC
18        if UserDefaults.standard.bool(forKey: "userLoggedIn") {
19            initialViewController = storyboard.instantiateViewController(withIdentifier: "HomeViewController")
20        } else {
21            initialViewController = storyboard.instantiateViewController(withIdentifier: "LoginViewController")
22        }
23        
24        // Initialize window
25        window = UIWindow(frame: UIScreen.main.bounds)
26        window?.rootViewController = initialViewController
27        window?.makeKeyAndVisible()
28        
29        return true
30    }
31}

Key Considerations

  • Performance: Instantiate only the view controllers required at start-up to prevent unnecessary memory usage.
  • Initialization Logic: Place any global initial setup logic before setting the initial view controller.
  • Testing: Write unit tests or UI tests to validate that the correct view controller is set under various conditions.

Alternatives to the AppDelegate Approach

  • SceneDelegate (iOS 13+): With the introduction of SceneDelegate, the method to set the initial view controller shifted from AppDelegate in some instances. The principle remains the same but is applied within the scene(_:willConnectTo:options:) method.

Table of Key Points

TopicExplanation
PurposeDynamic UI setups based on conditions (e.g., user status).
Where to implementAppDelegate or SceneDelegate methods, depending on iOS version.
Steps RequiredLoad storyboard, determine controller, set as root in window. Make visible.
Performance ConsiderationLoad only necessary controllers to optimize memory.
AlternativesUse SceneDelegate for newer iOS versions supporting multiple scenes.

By programmatically setting the initial view controller, developers gain flexibility in their app’s user interface flow, allowing for adaptive, user-centric designs and configurations. This method is advantageous in many scenarios, from handling user sessions to facilitating easier debugging during development.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.