Swift
iOS Development
viewController
Programming
Mobile Development

Instantiate and Present a viewController in Swift

Interview Questions practice on Codemia

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

Browse interview questions

Introduction

In Swift development, managing view controllers is essential for creating seamless and dynamic user interfaces. Instantiating and presenting view controllers enable developers to navigate between different screens in an application, handle complex UI flows, and present information in an organized manner. This article delves into the technicalities of instantiating and presenting view controllers using Swift, providing practical explanations and examples.

Instantiating View Controllers

View controllers in Swift are responsible for handling the user interface of a segment of an app. To use a view controller, you typically need to instantiate it. This involves creating an instance of the UIViewController class or its subclass, which may then be presented modally, pushed onto a navigation stack, or embedded in a container.

Instantiating from Storyboard

In many iOS applications, view controllers are defined in storyboards. To instantiate a view controller from a storyboard, you must first ensure the storyboard has a storyboard identifier set for the view controller.

Example

Assuming you have a storyboard named Main and a view controller within it with the identifier MyViewController:

swift
1// 1. Obtain reference to the UIStoryboard
2let storyboard = UIStoryboard(name: "Main", bundle: nil)
3// 2. Instantiate ViewController using its identifier
4if let myViewController = storyboard.instantiateViewController(withIdentifier: "MyViewController") as? MyViewController {
5    // 3. Use myViewController as needed
6}

Instantiating via Code

Sometimes view controllers are created entirely programmatically without using storyboards.

Example

swift
let myViewController = MyViewController()
// Configure properties on myViewController if needed

Presenting View Controllers

Once a view controller is instantiated, you may need to present it. The presentation methods in UIKit can vary based on your navigation structure (e.g., navigation stack, modal presentation).

Presenting Modally

Modal presentation is a common way to display content temporarily. The presented view controller covers the current context.

Example

swift
1let storyboard = UIStoryboard(name: "Main", bundle: nil)
2if let modalVC = storyboard.instantiateViewController(withIdentifier: "ModalViewController") as? ModalViewController {
3    // Prepare properties on modalVC if necessary
4    self.present(modalVC, animated: true, completion: nil)
5}

Pushing onto Navigation Stack

If your app uses a UINavigationController, you can push view controllers onto the navigation stack.

Example

swift
1let storyboard = UIStoryboard(name: "Main", bundle: nil)
2if let detailVC = storyboard.instantiateViewController(withIdentifier: "DetailViewController") as? DetailViewController {
3    // Assuming self is within a UINavigationController
4    self.navigationController?.pushViewController(detailVC, animated: true)
5}

Embedding in a Container

Embed a view controller within another using containment APIs if designing complex interfaces.

Example

swift
1func embedChildViewController() {
2    let childVC = ChildViewController()
3    self.addChild(childVC)
4    childVC.view.frame = self.view.bounds
5    self.view.addSubview(childVC.view)
6    childVC.didMove(toParent: self)
7}

Custom Transitions

For advanced UI designs, you may customize transitions between view controllers using UIViewControllerTransitioningDelegate and Core Animation.

swift
1class CustomTransitionDelegate: NSObject, UIViewControllerTransitioningDelegate {
2    // Define custom transition logic here
3}
4
5// Usage
6let customVC = CustomViewController()
7customVC.modalPresentationStyle = .custom
8customVC.transitioningDelegate = CustomTransitionDelegate()
9present(customVC, animated: true, completion: nil)

Table of Key Points

ConceptDetails
Storyboard InstantiationUtilize UIStoryboard and identifier to instantiate view controllers defined in storyboards.
Code InstantiationDirectly create instances of view controllers when entirely programmatic.
Modal PresentationUse present(_:animated:completion:) for temporary modals covering current view.
Navigation PushEmploy pushViewController(_:animated:) within UINavigationController for navigation flows.
Container EmbeddingUse containment APIs for organizing complex interfaces.
Custom TransitionsImplement custom transitions using UIViewControllerTransitioningDelegate for tailored animations.

Conclusion

Instantiating and presenting view controllers effectively are critical steps in building iOS applications with intuitive and efficient navigation paths. Whether you employ storyboards, navigate with navigation controllers, or present modally, understanding these concepts will significantly enhance your app's user experience. With the tools and methods outlined, you'll be well-equipped to create dynamic views that engage and guide users seamlessly through your app.


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.