how to use addChildViewController in subview

2020-03-27 13:58发布

问题:

I want to use addChildViewController in View (one view fro subviews array) but I don't know about that. this is my code :

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:????];
        }
    }

I don't know how to get UIViewController* from subview!!!!

回答1:

From Apple's Documentation :

(Here content is considered as child controller)

Adding another view controller’s view to the container’s view hierarchy

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

Here’s what the code does:

  1. It calls the container’s addChildViewController: method to add the child. Calling the addChildViewController: method also calls the child’s willMoveToParentViewController: method automatically.
  2. It accesses the child’s view property to retrieve the view and adds it to its own view hierarchy. The container sets the child’s size and position before adding the view; containers always choose where the child’s content appears. Although this example does this by explicitly setting the frame, you could also use layout constraints to determine the view’s position.
  3. It explicitly calls the child’s didMoveToParentViewController: method to signal that the operation is complete

So ,in your case you are trying to add ViewController to your view which doesn't work. The CartView should be a UIViewController not UIView