I am current developing an app in iPad. The app consist of only two views, but each view contains a lot of buttons and labels. Current, the layout of the two views is set. Each one is set in a view controller. I also have another view controller which contains the main menu on top and a big container(UIView) in which I hope it will be able to hold the two views I mentioned.
My question is, is there a way to show a view controller inside a view? I want to display one view controller inside that container(UIView) when I click on a button in the main menu, and display another when I click on another button. If my plan is not possible then please make some suggestions to make the same thing work.
Many Thanks!
Yes you can easily do it by adding the UIViewController view
like below..
_viewController=[self.storyboard instantiateViewControllerWithIdentifier:@"ViewController"];
[self.view addSubview:viewController.view];
As soon as you add viewController.view
your viewDidLoad
method inside ViewController
gets called.
Update: As per UIViewController Class Reference you need to add two more steps when adding a UIViewController as subview inside another ViewController.
[self addChildViewController:viewcontroller];
[self.view addSubview:viewController.view];
[viewcontroller didMoveToParentViewController:self];
Above completes the answer.
Hope this helps. Cheers.
Custom Container View Controllers are just what you need. If you use Interface Builder and storyboards - find a container view, drag it to your view and set the contained class to your view controller.
If you don't use storyboards, or IB (which i encourage you to do) - follow the link above and implement adding a child view controller to your view controller. Never ever add a subview without previous addChildViewController:
call, this may lead to unexpected results. Normally, adding a child view controller should be in this order:
[self addChildViewController:childvc]
[self.view addSubview:childvc.view]
[childvc didMoveToParentViewController:self]
In that case everything will work correctly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With