NEW: Master Swift design patterns with my latest book! >>

How to use view controller containment

Written by Paul Hudson    @twostraws

View controller containment allows you to embed one view controller inside another, which can simplify and organize your code. It takes four steps:

  1. Call addChildViewController() on your parent view controller, passing in your child.
  2. Set the child’s frame to whatever you need, if you’re using frames.
  3. Add the child’s view to your main view, along with any Auto Layout constraints.
  4. Call didMove(toParentViewController:) on the child, passing in your main view controller.

In Swift code it looks like this:

addChildViewController(child)
child.view.frame = frame
view.addSubview(child.view)
child.didMove(toParentViewController: self)

When you’re finished with it, the steps are conceptually similar but in reverse:

  1. Call willMove(toParentViewController:), passing in nil.
  2. Remove the child view from its parent.
  3. Call removeFromParentViewController() on the child.

In code, it’s just three lines:

willMove(toParentViewController: nil)
view.removeFromSuperview()
removeFromParentViewController()

Just for convenience you might want to consider adding a small, private extension to UIViewController to do these tasks for you – they do need to be run in a precise order, which is easily done incorrectly.

Something like this ought to do it:

@nonobjc extension UIViewController {
    func add(_ child: UIViewController, frame: CGRect? = nil) {
        addChildViewController(child)

        if let frame = frame {
            child.view.frame = frame
        }

        view.addSubview(child.view)
        child.didMove(toParentViewController: self)
    }

    func remove() {
        willMove(toParentViewController: nil)
        view.removeFromSuperview()
        removeFromParentViewController()
    }
}

That’s marked @nonobjc so it won’t conflict with any of Apple’s own code, now or in the future.

Available from iOS 5.0 – learn more in my book Swift Design Patterns

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

Upgrade to the premium experience

Get all 40 projects in PDF and ePub, plus exclusive content that will take your Swift learning to the next level – buy the Hacking with Swift book today!

Click here to visit the Hacking with Swift store >>