Adding child view controllers

Adding a child view controller is possible with the func addChild(_ childController: UIViewController) available on UIViewController instances. When using this function, you effectively create a strong relationship between the container view controller and the child view controller.

This relationship is necessary, in order to make sure that all the container view controller lifecycle calls are properly forwarded to the children. Doing so will ensure the child view controllers behave like standalone view controllers.

The following is a snippet that will help you safely add a child view controller with animations:

extension UIViewController {

func add(_ childController: UIViewController,
with animations: (() -> Void)? = nil,
duration: TimeInterval? = nil) {

view.addSubview(childController.view)
addChild(childController)

if let animations = animations,
let duration = duration {
UIView.animate(withDuration: duration, animations:
animations) { (done) in
childController.didMove(toParent: self)
}
} else {
childController.didMove(toParent: self)
}
}
}

The UIKit documentation (https://developer.apple.com/documentation/uikit/uiviewcontroller/1621405-didmove) specifies that you need to manually call didMove(toParent:) either right after adding the child view controller, or just after all transitions and animations have been performed.