Loading a view controller inside a view in Xcode

I am currently developing an application on an iPad. The application consists of only two types, but each view contains many buttons and labels. Current, the location of the two species is established. Each of them is installed in the view controller. I also have another view controller that contains the main menu at the top and a large container (UIView) in which I hope that it can hold the two opinions that I mentioned.

My question is: is there a way to show the view controller inside the view? I want to display one view controller inside this container (UIView) when I click a button in the main menu, and show another when I click on another button. If my plan is not possible, please take a few tips to do the same.

Thank you very much!

+6
source share
2 answers

Yes, you can easily do this by adding a UIViewController view , as shown below.

 _viewController=[self.storyboard instantiateViewControllerWithIdentifier:@"ViewController"]; [self.view addSubview:viewController.view]; 

Once you add viewController.view , your viewDidLoad method inside the ViewController is called.

Update: According to the UIViewController class reference, you need to add two more steps when adding a UIViewController as a subtask inside another ViewController.

 [self addChildViewController:viewcontroller]; [self.view addSubview:viewController.view]; [viewcontroller didMoveToParentViewController:self]; 

Above is the answer.

Hope this helps. Greetings.

+7
source

Custom container view controllers are what you need. If you use Interface Builder and storyboards, find the container view, drag it into your view and set the class contained in your controller. container view in objects library

If you are not using storyboards or IB (which I recommend), follow the link above and add the child view controller to your view controller. Never add a subview without a previous call to addChildViewController: this may lead to unexpected results. Typically, adding a child view controller should be in the following order:

  • call [self addChildViewController:childvc]
  • add child VC view as a preview [self.view addSubview:childvc.view]
  • call [childvc didMoveToParentViewController:self]

In this case, everything will work correctly.

+5
source

Source: https://habr.com/ru/post/989380/


All Articles