Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading a View Controller inside a View In Xcode

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!

like image 256
JLT Avatar asked Jun 19 '15 07:06

JLT


2 Answers

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.

like image 82
iphonic Avatar answered Sep 28 '22 04:09

iphonic


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.
container view in objects library

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:

  1. call [self addChildViewController:childvc]
  2. add child's VC view as a subview [self.view addSubview:childvc.view]
  3. call [childvc didMoveToParentViewController:self]

In that case everything will work correctly.

like image 27
Sega-Zero Avatar answered Sep 28 '22 06:09

Sega-Zero