Add a child view controller's view to a subview of the parent view controller

一个人想着一个人 提交于 2019-11-27 12:04:52
Anupdas

It doesn't really matter which view you are adding the child viewController to. If a view of a viewController is added to another viewController you need set it properly.

tableViewController.view.frame = self.contentView.bounds;
[self.contentView addSubview:tableViewController.view];
/*Calling the addChildViewController: method also calls 
the child’s willMoveToParentViewController: method automatically */
[self addChildViewController:tableViewController];
[tableViewController didMoveToParentViewController:self];

Source code

//class name InfoViewController

IBOutlet UIView *addViewToAddPlot;
InfoViewController *InfoController;

-(void) add_method
{
    InfoController = [[InfoViewController alloc] initWithNibName:@"InfoViewController" bundle:nil];
    InfoController.view.frame = self.addViewToAddPlot.bounds;

    [self containerAddChildViewController:InfoController];
}

-(void) remove_method
{
    [self containerRemoveChildViewController : InfoController];
}

- (void)containerAddChildViewController:(UIViewController *)childViewController {

    [self addChildViewController:childViewController];
    [self.addViewToAddPlot addSubview:childViewController.view];
    [childViewController didMoveToParentViewController:self];

}

- (void)containerRemoveChildViewController:(UIViewController *)childViewController {

    [childViewController willMoveToParentViewController:nil];
    [childViewController.view removeFromSuperview];
    [childViewController removeFromParentViewController];

}

Add and remove viewcontroller ,#childviewcontroller

To show a child_view_controller over a main_view_controller.

step 1: create a main_view_controller in storyboard.

step 2: create a child_view_controller with a UIview and some Label inside in storyboard.

step 3: in main_view_controller's button action add the following code:

- (IBAction)YourButtonAction:(id)sender {
    ChildViewControllerName *childViewControllerName = [self.storyboard instantiateViewControllerWithIdentifier:@"storyboardIdYouProvided"];
    childViewControllerName.view.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y, self.view.frame.size.width, self.view.frame.size.height);
    [self.view addSubview:childViewControllerName.view];
    [childViewControllerName didMoveToParentViewController:self];
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!