I have a UIViewController (DetailViewController) consisting of a navigation bar on the top and a UIView covering the rest of the screen. Is it possible to control the UIView with a UIViewController other than DetailViewController?
Asked
Active
Viewed 7,125 times
3 Answers
8
You can do this, but you must not forget to call Apple's required methods for embedding UIViewControllers. Otherwise, your view controller will not get called by the OS to handle certain events.
To add the view controller:
[self addChildViewController:childViewController];
[self.view addSubview:childViewController.view];
[childViewController didMoveToParentViewController:self];
To remove the view controller:
[childViewController willMoveToParentViewController:nil];
[childViewController.view removeFromSuperview];
[childViewController removeFromParentViewController];
Related documentation:
- Implementing a Container View Controller in the UIViewController Class Reference
- Implementing a Container View Controller in the View Controller Programming Guide for iOS
See this question for more information.
1
You can also do all this in storyboard. Just drag a container view out into your main view controller and use the embed segue from it to your embedded view controller. It will properly set up all the view controller hierarchy for you.

rvijay007
- 1,357
- 12
- 20
0
In Swift 5.3 You can use the following extension:
extension UIViewController {
/// Embeds a UIViewController inside of another UIViewController using its view.
/// - Parameters:
/// - Parameter viewController: UIViewController to embed
/// - Parameter frame: A frame to be used. Nil by default and used view's frame.
func embed(viewController: UIViewController, frame: CGRect? = nil) {
addChild(viewController)
view.addSubview(viewController.view)
viewController.view.frame = view.bounds
viewController.didMove(toParent: self)
}
/// Removes an embedded UIViewController from a UIVIewController
/// - Parameters:
/// - Parameter embeddedViewController: UIViewController to remove
func remove(embeddedViewController: UIViewController) {
guard children.contains(embeddedViewController) else {
return
}
embeddedViewController.willMove(toParent: nil)
embeddedViewController.view.removeFromSuperview()
embeddedViewController.removeFromParent()
}
}

Reimond Hill
- 4,278
- 40
- 52