Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Embed" UIViewController within another

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?

like image 608
danielmhanover Avatar asked Oct 20 '25 04:10

danielmhanover


2 Answers

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.

like image 128
Senseful Avatar answered Oct 22 '25 19:10

Senseful


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.

like image 29
rvijay007 Avatar answered Oct 22 '25 18:10

rvijay007



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!