Embedding View Controllers

In John Sundell’s excellent article Using child view controllers as plugins in Swift, Mr. Sundell reminds us that Apple has given us the ability to compose UIViewController objects together, allowing multiple controllers to display in one view. He also gave us two helper functions to use, one to add a child view controller and the other to remove it. Here is the the function to add a child controller to another controller:

1
2
3
4
5
func add(_ child: UIViewController) {
    addChildViewController(child)
    view.addSubview(child.view)
    child.didMove(toParentViewController: self)
}

It is definitely a handy function. When I wanted to use it, however, it fell short. My parent view controller wasn’t displaying the child view controller full screen but rather just in a view – a smaller area than the full screen. So I modified the add function to be like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
func add(_ child: UIViewController, using container: UIView? = nil) {
    addChildViewController(child)
    if let container = container {
        container.addSubview(child.view)
    }
    else {
        view.addSubview(child.view)
    }
    child.didMove(toParentViewController: self)
}

func exampleUsage() {
    let parentController = MyViewController()
    // assume "MyViewController" contains a view "holder" that
    // we want the child to be placed in
    let childController = UIViewController()</p>
    parentController.add( childController, using: parentController.holder )
}

I don’t know if anyone else out there is experimenting with composing view controllers, but I hope you found my experience handy.

Gist Version of This Article