0%

操作子视图控制器

操作子视图控制器

系统提供了一些方法用于添加和移除子视图控制器:
(UIContainerViewControllerProtectedMethods)类别里的:

1
2
3
- (void)addChildViewController:(UIViewController *)childController NS_AVAILABLE_IOS(5_0);
- (void)removeFromParentViewController NS_AVAILABLE_IOS(5_0);

上述两个方法调用后还要配套调用(UIContainerViewControllerCallbacks)类别里的:

1
2
- (void)willMoveToParentViewController:(nullable UIViewController *)parent NS_AVAILABLE_IOS(5_0);
- (void)didMoveToParentViewController:(nullable UIViewController *)parent NS_AVAILABLE_IOS(5_0);

addChildViewController:的说明:

  1. If the child controller has a different parent controller, it will first be removed from its current parent
    by calling removeFromParentViewController.

  2. addChildViewController: will call [child willMoveToParentViewController:self] before adding the
    child. However, it will not call didMoveToParentViewController:.所以willMoveToParentViewController:就不需要我们自己调用了,但需要我们自己手动调用didMoveToParentViewController:

removeFromParentViewController的说明:

removeFromParentViewController does not call [self willMoveToParentViewController:nil] before removing the
child. This is also the responsibilty of the container subclass.subclasses will typically define a method that removes a child in
the reverse manner by first calling [child willMoveToParentViewController:nil].

正确添加和移除一个子视图控制器

添加一个子视图控制器的方法如下:

1
2
3
4
5
[self addChildViewController:quizingVC];
quizingVC.view.frame = CGRectMake(0, 0, self.contentScrollView.frame.size.width, self.contentScrollView.frame.size.height - 2*matchStatusBarH);
[self.contentScrollView addSubview:quizingVC.view];
[quizingVC didMoveToParentViewController:self];

移除一个子视图控制器:

1
2
3
4
5
6
7
8
//先将其父控制器置为nil
[self willMoveToParentViewController:nil];

//其他一些操作比如动画.
...

//再remove
[self removeFromParentViewController];

note

一个控制器只有被添加到父控制器后,父控制器的view的frame(尤其是size)改变时,系统才会调整子控制器的View的frame,并随之自动调用子控制器的viewDidLayoutSubviews方法.这样子控制器的View及其子视图才会有正确的frame.

在嵌套控制器的时候可以测试一下.比如使用CAPSPageMenu第三方库.

觉得文章有帮助可以打赏一下哦!