将子视图控制器的视图添加到父视图控制器的子视图中

我想添加一个tableViewController作为一个containerViewController的子视图控制器(如下所示)。 根据苹果公司的视图控制器编程指南,我可以通过在我的containerViewController里面的以下几行代码来实现:

[self addChildViewController:tableViewController]; [self.view addSubview:tableViewController.view]; [tableViewController didMoveToParentViewController:self]; 

事实上,这工作正常。 现在的问题是,我不想添加tableViewController的视图作为containerViewController的根视图的子视图。 相反,我想添加它作为containerView的子视图(见图),它本身是containerViewController的根视图的子视图。 所以我改变了上面的代码如下:

  [self addChildViewController:tableViewController]; [self.contentView addSubview:tableViewController.view]; [tableViewController didMoveToParentViewController:self]; 

现在,当我启动应用程序,它立即崩溃,这个错误:

终止应用程序由于未捕获的exception'UIViewControllerHierarchyInconsistency',原因:'子视图控制器:应该有父视图控制器:但实际的父母是:'

这里有什么问题? 是不是可以添加一个childViewController的视图到其containerViewController的特定视图? 或者我怎么能实现这个没有在视图控制器层次结构中的错误?

containerViewController

添加子视图控制器到哪个视图并不重要。 如果viewController的视图添加到另一个viewController,你需要正确设置它。

 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]; 

源代码

 //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]; } 

添加和删​​除viewcontroller,#childviewcontroller

在main_view_controller上显示一个child_view_controller。

第1步 :在故事板中创build一个main_view_controller。

第2步 :在storyboard中创build一个带UIview和一些Labelchild_view_controller

第3步 :在main_view_controller的button操作中添加如下代码:

 - (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]; }