Once you have added view controllers to a container controller, you may want to remove them if the relationship between those controllers is no longer needed. For example you may want to animate a child view controller through custom transitioning from one view controller to another, and back again. When performing such a transition, you will need to do the following:
- Remove the child controller(s) from their container controller
- Add the child to the next owning controller
When performing the operation on the way back, you will need to perform those steps in the opposite order:
extension UIViewController {
func remove(_ childController: UIViewController,
with animations: (() -> Void)? = nil,
duration: TimeInterval? = nil) {
childController.willMove(toParent: nil)
if let animations = animations,
let duration = duration {
UIView.animate(withDuration: duration, animations: animations) { (done) in
childController.view.removeFromSuperview()
childController.removeFromParent()
}
} else {
childController.view.removeFromSuperview()
childController.removeFromParent()
}
}
}
This extension will help you properly remove a child controller and its view, with or without animations, and will always ensure that all methods are properly called. Note that it's implemented on UIViewController but is never itself used. It can be implemented as a static method, or right on the child controller itself.