addChildViewController

将子视图控制器添加到一个视图容器中的步骤

  1. Call the addChildViewController: method of your container view controller.

    This method tells UIKit that your container view controller is now managing the view of the child view controller.

  2. Add the child’s root view to your container’s view hierarchy.

    Always remember to set the size and position of the child’s frame as part of this process.

  3. Add any constraints for managing the size and position of the child’s root view.

  4. Call the didMoveToParentViewController: method of the child view controller.

代码示例:

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

从父视图控制器中删除子视图控制器的步骤

  1. Call the child’s willMoveToParentViewController: method with the value nil.

  2. Remove any constraints that you configured with the child’s root view.

  3. Remove the child’s root view from your container’s view hierarchy.

  4. Call the child’s removeFromParentViewController method to finalize the end of the parent-child relationship.

代码示例:

- (void) hideContentController: (UIViewController*) content {
   [content willMoveToParentViewController:nil];
   [content.view removeFromSuperview];
   [content removeFromParentViewController];
}

在两个子视图控制器之间进行转换带动画效果

- (void)cycleFromViewController: (UIViewController*) oldVC
               toViewController: (UIViewController*) newVC {
   // Prepare the two view controllers for the change.
   [oldVC willMoveToParentViewController:nil];
   [self addChildViewController:newVC];
 
   // Get the start frame of the new view controller and the end frame
   // for the old view controller. Both rectangles are offscreen.
   newVC.view.frame = [self newViewStartFrame];
   CGRect endFrame = [self oldViewEndFrame];
 
   // Queue up the transition animation.
   [self transitionFromViewController: oldVC toViewController: newVC
        duration: 0.25 options:0
        animations:^{
            // Animate the views to their final positions.
            newVC.view.frame = oldVC.view.frame;
            oldVC.view.frame = endFrame;
        }
        completion:^(BOOL finished) {
           // Remove the old view controller and send the final
           // notification to the new view controller.
           [oldVC removeFromParentViewController];
           [newVC didMoveToParentViewController:self];
        }];
}

你可能感兴趣的:(addChildViewController)