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

Generic UI: Input<T>

For quite some time I’ve been bothered by the small use of generics in Apple’s iOS libraries. Third party libraries also typically make little use of generics. Generic typing is a fantastic feature of Objective-C and Swift. It allows... Continue →