Skip to content

Instantly share code, notes, and snippets.

@henning-jh
Last active March 19, 2018 13:37
Show Gist options
  • Save henning-jh/cc9267298efc93bf0b60536c0d731154 to your computer and use it in GitHub Desktop.
Save henning-jh/cc9267298efc93bf0b60536c0d731154 to your computer and use it in GitHub Desktop.
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:

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:

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment