JLT
JLT

Reputation: 3172

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!

Upvotes: 7

Views: 12842

Answers (2)

iphonic
iphonic

Reputation: 12719

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.

Upvotes: 12

Sega-Zero
Sega-Zero

Reputation: 3017

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.

Upvotes: 8

Related Questions