58

我正在尝试使用iOS5新方法创建容器视图控制器,例如addChildViewController.

我必须打电话addSubview后打电话addChildViewController吗?

打电话removeFromSuperview之前必须先打电话removeChildViewController吗?

我在 Apple 文档中没有看到任何关于此的内容。你怎么看?

4

4 回答 4

84

1) 调用 addChildViewController 后是否必须调用 addSubview?

是的

2) 在调用removeChildViewController 之前我必须调用removeFromSuperview 吗?

不完全的

你应该打电话removeFromParentViewController:而不是removeChildViewController: 你也应该打电话willMoveToParentViewController:

对于添加/删除,您可以参考这个伟大的类别:

UIViewController + 容器

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

}

developer.apple.com 上的官方资源

于 2013-04-20T21:19:26.990 回答
43

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).

于 2012-04-13T18:09:31.943 回答
3

addChildViewController添加到彼得的答案:我之前发现调用的一个原因addSubview是,当addSubview调用时viewDidLoad,子调用的调用,在某些情况下,您将希望在那时正确设置父子层次结构。如果不这样做,在孩子的 viewDidLoad 期间 parentViewController 属性将为零。

于 2014-09-15T15:33:49.990 回答
0

以下是 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

这将使您了解子视图控制器和父视图控制器的关系以及如何使用它们。

于 2019-06-12T06:11:02.883 回答