如何在子视图中使用addChildViewController

时间:2015-06-17 15:07:00

标签: objective-c uiview uiviewcontroller subview

我想在addChildViewController中使用View(来自子视图数组的一个视图),但我不知道。这是我的代码:

for (UIView *subview in self.view.subviews) {
        if (subview.tag == 1) {
            CartView *cart = [[CartView alloc]init];

            [cart willMoveToParentViewController:????];/* (UIViewController*) from subview*/
            [cart.view setFrame:CGRectMake(0.0f,CGRectGetHeight(self.view.frame),CGRectGetWidth(self.view.frame),CGRectGetHeight(self.view.frame))];
            [UIView beginAnimations:nil context:nil];
            [UIView setAnimationDuration:0.3];
            [cart.view setFrame:CGRectMake(0.0f,0,CGRectGetWidth(self.view.frame),CGRectGetHeight(self.view.frame))];
            [UIView commitAnimations];
            [subview addSubview:cart.view];
            [???? addChildViewController:cart];
            [cart didMoveToParentViewController:????];
        }
    }

我不知道如何从子视图获取UIViewController * !!!!

1 个答案:

答案 0 :(得分:4)

来自Apple的文档:

(此处内容被视为子控制器)

将另一个视图控制器的视图添加到容器的视图层次结构

- (void) displayContentController: (UIViewController*) content;
{
   [self addChildViewController:content];                 // 1
   content.view.frame = [self frameForContentController]; // 2
   [self.view addSubview:self.currentClientView];
   [content didMoveToParentViewController:self];          // 3
}

以下是代码的作用:

  1. 它调用容器的addChildViewController:方法来添加子项。调用addChildViewController:方法也会自动调用子节点的willMoveToParentViewController:方法。
  2. 它访问子视图属性以检索视图并将其添加到自己的视图层次结构中。容器在添加视图之前设置子项的大小和位置;容器总是选择孩子的内容出现的位置。虽然此示例通过显式设置框架来执行此操作,但您也可以使用布局约束来确定视图的位置。
  3. 它显式调用子的didMoveToParentViewController:方法来表示操作已完成
  4. 因此,在您的情况下,您尝试将ViewController添加到您的视图中,这不起作用。 CartView应为UIViewController而不是UIView