It’s easy to forget which order to send the messages when adding a child view controller for containment in another parent view controller. Here’s a straight to the point look-up when you need it.
Adding a child view controller
parent.addChildViewController(child) parent.view.addSubview(child.view) child.didMoveToParentViewController(parent)
Removing a child view controller
child.willMoveToParentViewController(nil) child.view.removeFromSuperview() child.removeFromParentViewController()
Extending UIViewController for convenience
With this extension, adding a child is simplified to parent.addContainedChildViewController(child). Then when removing the child, all that needs to be done is child.breakContainment().
extension UIViewController { | |
/** | |
Convenience function to add a child view controller to self. | |
This will send the proper notifications to the child view controller | |
and add the child view controller's view to `self.view`. | |
- parameter child: The view controller that should be contained in `self`. | |
*/ | |
func addContainedChildViewController(child: UIViewController) { | |
addContainedChildViewController(child, inView: view) | |
} | |
/** | |
Convenience function to add a child view controller to self. | |
This will send the proper notifications to the child view controller | |
and add the child view controller's view to the provided `parentView`. | |
- parameter child: The view controller that should be contained in `self`. | |
- parameter parentView: The view in which to add the child's view. | |
*/ | |
func addContainedChildViewController(child: UIViewController, inView parentView: UIView) { | |
addChildViewController(child) | |
parentView.addSubview(child.view) | |
child.didMoveToParentViewController(self) | |
} | |
/** | |
Convenience function to break containment with a parent view controller. | |
Calling this on a child/contained view controller will call the | |
proper methods to have it removed. It will send the proper notifications | |
to the child view controller. | |
*/ | |
func breakContainment() { | |
willMoveToParentViewController(nil) | |
view.removeFromSuperview() | |
removeFromParentViewController() | |
} | |
} |