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

Anagrams/C++

This weekend I decided to refresh on C++ in preparation for some interviews. I tried to pick a project that I could code in roughly one day. It should not only have me review C++ but force me to solve some problems and implement some... Continue →