View Containment in Swift

I’m always looking for this code snippet around and for some reason it doesn’t pop on Google that easily so I thought I’d post the 4 lines of code necessary for achieving view containment in Swift (this is Swift 4 by the way):

override func viewDidLoad() {
    super.viewDidLoad()

    // View containment
    addChild(childViewController)
    childViewController.view.frame = view.bounds
    view.addSubview(childViewController.view)
    childViewController.didMove(toParent: self)
}

What’s view containment you ask? it’s when you replace the view of a view / view controller with the view of another view controller. It’s incredibly useful for many use cases. One use case is: you want to build a view controller that can serve as a router and display one of multiple view controllers based on some logic. Another use case is if you want to overlay something on top of a view controller without adding a subview on that view controller, eg. building a custom tab controller.

Edit: (June 1, 2019)
I forgot a small detail. If your device rotates or some things move causing views to be laid out again, then the child view controller that is contained in the superview may not be the right dimensions! to handle this, simply add:

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    childViewController.view.frame = view.bounds
}

This ensures the child view controller is always the sized correctly.

 
8
Kudos
 
8
Kudos

Now read this

Working Remote From Nha Trang, Vietnam

Recently I went to Vietnam to visit some family and stayed in Nha Trang for a little over 2 weeks. Very luckily Square is flexible on work schedules and work locations. Additionally my manager allowed me to work from Vietnam, and I did... Continue →