我正在尝试使用iOS5
新方法创建容器视图控制器,例如addChildViewController
.
我必须打电话addSubview
后打电话addChildViewController
吗?
打电话removeFromSuperview
之前必须先打电话removeChildViewController
吗?
我在 Apple 文档中没有看到任何关于此的内容。你怎么看?
我正在尝试使用iOS5
新方法创建容器视图控制器,例如addChildViewController
.
我必须打电话addSubview
后打电话addChildViewController
吗?
打电话removeFromSuperview
之前必须先打电话removeChildViewController
吗?
我在 Apple 文档中没有看到任何关于此的内容。你怎么看?
1) 调用 addChildViewController 后是否必须调用 addSubview?
是的
2) 在调用removeChildViewController 之前我必须调用removeFromSuperview 吗?
不完全的
你应该打电话removeFromParentViewController:
而不是removeChildViewController:
你也应该打电话willMoveToParentViewController:
对于添加/删除,您可以参考这个伟大的类别:
- (void)containerAddChildViewController:(UIViewController *)childViewController {
[self addChildViewController:childViewController];
[self.view addSubview:childViewController.view];
[childViewController didMoveToParentViewController:self];
}
- (void)containerRemoveChildViewController:(UIViewController *)childViewController {
[childViewController willMoveToParentViewController:nil];
[childViewController.view removeFromSuperview];
[childViewController removeFromParentViewController];
}
Short answer: "Yes, and yes." The view hierarchy and the view controller hierarchy are still independent. The containment API simply allows views from other controllers to present themselves within a parent controller's view in a clean and consistent way.
You can find a bit in Apple's docs here... this is a relevant passage from the "Container View Controllers Arrange Content of Other View Controllers" section:
A container manages a view hierarchy just as other view controllers do. A container can also add the views of any of its children into its view hierarchy. The container decides when such a view is added and how it should be sized to fit the container’s view hierarchy, but otherwise the child view controller remains responsible for the view and its subviews.
If you have access, I would highly recommend checking out the WWDC 2011 video entitled "Implementing UIViewController Containment" (download it from Apple Developer Video Archive).
addChildViewController
添加到彼得的答案:我之前发现调用的一个原因addSubview
是,当addSubview
调用时viewDidLoad
,子调用的调用,在某些情况下,您将希望在那时正确设置父子层次结构。如果不这样做,在孩子的 viewDidLoad 期间 parentViewController 属性将为零。
以下是 Apple 文档提供的示例。
- (void) displayContentController: (UIViewController*) content {
[self addChildViewController:content];
content.view.frame = [self frameForContentController];
[self.view addSubview:self.currentClientView];
[content didMoveToParentViewController:self];
}
您还可以查看此处给出的详细说明 - https://developer.apple.com/library/archive/featuredarticles/ViewControllerPGforiPhoneOS/ImplementingaContainerViewController.html
这将使您了解子视图控制器和父视图控制器的关系以及如何使用它们。