Logo for tanaschita.com

Quick tip on adding child view controllers programmatically

An extension that calls all necessary methods for adding a child view controller

15 Feb 2020 · 2 min read

To better separate and organize our code, we can nest view controllers inside each other.

The following code snippet provides an extension method that calls all necessary methods for adding a child view controller programmatically.

Besides calling the appropriate methods, the method also sets the constraints of the child view controller’s view.

extension UIViewController {
/// Utility method to add a `UIViewController` instance to a `UIView`.
/// Calls all necessary methods for adding a child view controller and set the constraints
/// between the views.
/// - Parameters:
/// - viewController: `UIViewController` instance that will be added to `contentView`.
/// - contentView: `UIView` that will add the `childViewController` as its subview.
func add(childViewController viewController: UIViewController, to contentView: UIView) {
let matchParentConstraints = [
viewController.view.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
viewController.view.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
viewController.view.topAnchor.constraint(equalTo: contentView.topAnchor),
viewController.view.bottomAnchor.constraint(equalTo: contentView.bottomAnchor)
viewController.view.translatesAutoresizingMaskIntoConstraints = false
viewController.didMove(toParent: self)
Sponsorship logo
Join the FREE iOS Architect Crash Course (for a limited time!)
If you’re a mid/senior iOS developer who’s looking to improve both your skills and salary level, then join this 100% free online crash course. Hurry up because it's available only until November 27th!
Click to get it now


Image of a reading marmot

Like to support my work?

Say hi

Related tags

Articles with related topics





SF Symbols guide for SwiftUI and UIKit

Learn how to use symbol images provided by Apple in iOS applications.

31 Jan 2022 · 5 min read

Latest articles and tips

© 2022 tanaschita.com

Privacy policy