我想添加一个 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 层次结构中不出错的情况下实现此目的?
最佳答案
将子 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];
关于ios - 将 subview Controller 的 View 添加到父 View Controller 的 subview ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17011579/