set initial viewcontroller in appdelegate - swift
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
In a Swift application using UIKit, the AppDelegate
plays a crucial role in launching the app and setting up the main window. One important task is setting the initial view controller, which serves as the starting point for the user interface of the application. This process involves configuring the window and making key decisions about which view controller to display first.
Understanding the Application Lifecycle
When an iOS application launches, the system calls several methods in the AppDelegate
class to set up the app's environment. Among these methods, application(_:didFinishLaunchingWithOptions:)
is particularly important as it signals that the app has nearly completed its launching process.
Setting the Initial ViewController
To set the initial view controller in AppDelegate
, you primarily interact with the UIWindow object. Here’s a technical breakdown of the steps involved:
- Create a UIWindow instance: The application’s main window is an instance of UIWindow, and you need to create and assign this window to the app's
windowproperty. - Choose the Root ViewController: Decide which view controller should be the initial interface that the user sees. This could be a
UIViewController,UINavigationController, or any custom controller you've created. - Configure the Root ViewController: Initialize the root view controller and assign it as the root for the window. This setup might also include setting up navigation stacks, tab bars, or other controller hierarchies.
- Make the Window Key and Visible: Finally, call
makeKeyAndVisible()on the window to display it and receive user interactions.
Below is a Swift code example demonstrating these steps in AppDelegate
:
- Storyboard Support:
- Conditional Initial View Controllers:
- SceneDelegate for Modern iOS Apps:
Related reading
- Set inputType for an EditText Programmatically?
- Set margins in a LinearLayout programmatically
- Set margins in a LinearLayout programmatically
- Set operations union, intersection on Swift array?
- Set padding for UITextField with UITextBorderStyleNone
- Set rootViewController of UINavigationController by method other than initWithRootViewController
- Set selected item of spinner programmatically
- Set style for TextView programmatically
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack 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.