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.

 
5
Kudos
 
5
Kudos

Now read this

Design Houses with Minecraft

I’ve always wanted to build my own house. I’m an outlier and a software engineer. When I look at most houses I see inconsistent design, lines that don’t align, colors that don’t match, materials that don’t last, inefficient space use,... Continue →