ios - 将 subview Controller 的 View 添加到父 View Controller 的 subview

标签 ios addsubview parentviewcontroller container-view childviewcontroller

我想添加一个 tableViewController 作为 containerViewController 的 subview Controller (如下所示)。根据 Apple 的 View Controller Programming Guide我可以通过我的 containerViewController 中的以下代码行实现这一点:

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

事实上,这很好用。现在的问题是我不想将 tableViewController 的 View 添加为 containerViewController 的 Root View 的 subview 。相反,我想将它添加为 containerView 的 subview (参见图像),它本身是 containerViewController 的 Root View 的 subview 。所以我把上面的代码改成如下:

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

现在,当我启动该应用程序时,它立即崩溃并出现此错误:

Terminating app due to uncaught exception 'UIViewControllerHierarchyInconsistency', reason: 'child view controller: should have parent view controller: but actual parent is:'

这里有什么问题?是否无法将 childViewController 的 View 添加到其 containerViewController 的特定sub View ?或者如何在 View Controller 层次结构中不出错的情况下实现此目的?

containerViewController

最佳答案

将子 viewController 添加到哪个 View 并不重要。如果将 viewController 的 View 添加到另一个 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];

Source code

关于ios - 将 subview Controller 的 View 添加到父 View Controller 的 subview ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17011579/

相关文章:

ios - 如何从 Facebook + Swift + Parse 获取封面照片

ios - 在 Objective-C 中定义一个位置矩形

iOS UIView 在整个代码中添加和删除 subview

iphone - 添加 subview 后 superview 和parentviewcontroller nil

iphone - uialertview 被多次调用

ios - 如何使用导航 Controller 创建静态 subview ?

ios - 从一个 View 中删除一个 View 并将其添加到另一个 View

ios - 将 UIImageview 添加到 subview 后无法单击 UIAlertView 中的按钮

ios - 从父级重新加载 TableViewController

iPad:呈现模态视图,而我的 parentViewController 现在为零?