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

Meeting Knuth

I met Don Knuth in 2007 when I was 17. He owed me $2.56 and I wanted to trade my finding for the check in person, with the hope that I could shake his hand and maybe get a couple books signed. Dr. Donald Knuth is a famous Computer... Continue →