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

How to use view controller containment

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.

Master iOS 11 now!

My book Practical iOS 11 gives you seven complete coding projects that teach all the major new features in iOS 11 in a smart, practical way.

MASTER SWIFT NOW
Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Practical iOS 11 Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Click here to visit the Hacking with Swift store >>