美文网首页iOS 开发之旅
父子控制器详细解析(一)

父子控制器详细解析(一)

作者: 刀客传奇 | 来源:发表于2017-09-25 22:56 被阅读57次

    版本记录

    版本号 时间
    V1.0 2017.09.25

    前言

    在APP中很多时候我们都需要用到父子控制器来达到我们的需求,这个用的次数不是很频繁,但是在大的项目中搭建架构的时候还是会用到的,接下来我们就详细的解析一下父子控制器。相关代码已发到 Github - 刀客传奇

    几个基本概念

    1. 定义

    父子控制器,指的是一个控制器通过addChildViewController:方法添加多个控制器,被添加的控制器称为子控制器,添加多个子控制器的控制器称为父控制器。

    2. 父子控制器关系

    • 父控制器处理的事件会自动传递给子控制器。
    • 子控制器处理的事件会自动传给父控制器。
    • 子控制器可以通过属性parentViewController获取父控制器 。
    • 父控制器可以通过属性childViewControllers获取所有子控制器。
    • A控制器添加到B控制器上后,A控制器就会被强引用,即使A控制器的view不正在显示,A控制器和A控制器的view都不会被销毁。

    3. 什么时候使用父子控制器?

    当Apple提供的框架不能满足开发者的时候,考虑重新搭建框架。比如UITabBarControllertabBar默认是在底部,想要把它放到顶部或者左边,实现起来会很困难,这时考虑到模仿UITabBarController的功能,搭建新的框架可能会更简单。

    4. 创建父子控制器方法

    一个控制器使用addChildViewController:方法添加子控制器。

    如果两个控制器的视图View是父子关系,那么这两个控制器也应该是父子关系,也就是说应该利用代码创建父子关系。

    5. 父子控制器优点和注意事项

    • 当父控制器发生一些重大的事件,可以通知到子控制器,比如说屏幕旋转。

    • 不要自己创建数组来管理子控制器,用 UIViewController 自带的 childViewControllers 数组可以避免掉很多不必要的麻烦。

    • 可以在整体布局中嵌套一个scrollview,使子控制器可以进行滑动切换,实现类似网易新闻和今日头条不同频道加载的效果。

    6. 父子控制器的接口及几个重要方法

    下面我们要看一下父子控制器需要的几个重要方法。

    • addChildViewController添加子控制器,建立父子关系
      • 如果重写此方法,必须在实现中调用父类实现
      • 调用addChildViewController:会自动调用child的willMoveToParentViewController:方法,不会自动调用didMoveToParentViewController方法;
      • 如果childController已经有一个不同的父控制器,那么它将首先通过调用removeFromParentViewController从当前的父控制器移除。
      • 如果一个父控制器的内容中包含了另一个控制器的view,那么父子控制器的关系是必要的.
    /*
      If the child controller has a different parent controller, it will first be removed from its current parent
      by calling removeFromParentViewController. If this method is overridden then the super implementation must
      be called.
    */
    - (void)addChildViewController:(UIViewController *)childController NS_AVAILABLE_IOS(5_0);
    
    • removeFromParentViewController从父控制器中移除子控制器
      • 将控制器从父控制器的子控制器数组中移除;如果重写此方法,必须在实现中调用父类实现。
    /*
      Removes the the receiver from its parent's children controllers array. If this method is overridden then
      the super implementation must be called.
    */
    - (void)removeFromParentViewController NS_AVAILABLE_IOS5_0);
    
    • willMoveToParentViewController将要添加到父控制器。

      • 此方法会在视图控制器被添加或移除之前调用。
      • 自定义容器类控制器在调用child的removeFromParentViewController方法前,必须先调用child的willMoveToParentViewController:nil方法;
      • 如果重写此方法,必须在实现中调用父类实现;
      • 将要从parent移除时,参数传递nil,将要添加到parent时,参数传父控制器;调用addChildViewController:会自动调用child的willMoveToParentViewController:方法,但不会自动调用didMoveToParentViewController方法,可以在子控制器过渡完成时手动调用didMoveToParentViewController,或者在没有过渡效果时直接手动调用didMoveToParentViewController;同样的,removeFromParentViewController方法不会自动调用[self willMoveToParentViewController:nil]而需要我们手动进行调用,但会自动调用didMoveToParentViewController方法。
    • didMoveToParentViewController添加到父控制器

      • 此方法会在视图控制器被添加或移除之后调用;
      • 自定义容器类控制器在调用addChildViewController方法之后,必须调用child的didMoveToParentViewController:parent方法,如果有过渡过程,需要在过渡完成之后调用,否则直接调用;
      • 如果重写此方法,必须在实现中调用父类实现;
    /*
      These two methods are public for container subclasses to call when transitioning between child
      controllers. If they are overridden, the overrides should ensure to call the super. The parent argument in
      both of these methods is nil when a child is being removed from its parent; otherwise it is equal to the new
      parent view controller.
    
      addChildViewController: will call [child willMoveToParentViewController:self] before adding the
      child. However, it will not call didMoveToParentViewController:. It is expected that a container view
      controller subclass will make this call after a transition to the new child has completed or, in the
      case of no transition, immediately after the call to addChildViewController:. Similarly,
      removeFromParentViewController does not call [self willMoveToParentViewController:nil] before removing the
      child. This is also the responsibilty of the container subclass. Container subclasses will typically define
      a method that transitions to a new child by first calling addChildViewController:, then executing a
      transition which will add the new child's view into the view hierarchy of its parent, and finally will call
      didMoveToParentViewController:. Similarly, subclasses will typically define a method that removes a child in
      the reverse manner by first calling [child willMoveToParentViewController:nil].
    */
    - (void)willMoveToParentViewController:(nullable UIViewController *)parent NS_AVAILABLE_IOS(5_0);
    - (void)didMoveToParentViewController:(nullable UIViewController *)parent NS_AVAILABLE_IOS(5_0);
    
    • transitionFromViewController控制器转场
      • 此方法用于在不同的子控制器之间过渡。
      • 过渡完成时,toViewController的view将被添加到fromViewController的view的父视图上,fromViewController的view将被从父视图上移除;
      • 对于iOS本来的容器类控制器例如导航控制器与TabbarController,请不要调用此方法;
        也可以直接用UIView的API,但是要确保,在fromViewController的view移除时toViewController的view已经被添加到了视图层级中;
      • 此方法底层中实现的顺序是:添加toViewController的view,执行动画,动画完成时移除fromViewController的view;
      • 如果重写此方法,必须在实现中调用父类实现。
    /*
      This method can be used to transition between sibling child view controllers. The receiver of this method is
      their common parent view controller. (Use [UIViewController addChildViewController:] to create the
      parent/child relationship.) This method will add the toViewController's view to the superview of the
      fromViewController's view and the fromViewController's view will be removed from its superview after the
      transition completes. It is important to allow this method to add and remove the views. The arguments to
      this method are the same as those defined by UIView's block animation API. This method will fail with an
      NSInvalidArgumentException if the parent view controllers are not the same as the receiver, or if the
      receiver explicitly forwards its appearance and rotation callbacks to its children. Finally, the receiver
      should not be a subclass of an iOS container view controller. Note also that it is possible to use the
      UIView APIs directly. If they are used it is important to ensure that the toViewController's view is added
      to the visible view hierarchy while the fromViewController's view is removed.
    */
    - (void)transitionFromViewController:(UIViewController *)fromViewController toViewController:(UIViewController *)toViewController duration:(NSTimeInterval)duration options:(UIViewAnimationOptions)options animations:(void (^ __nullable)(void))animations completion:(void (^ __nullable)(BOOL finished))completion NS_AVAILABLE_IOS(5_0);
    

    一个简单实例

    下面我们就看一个简单实例,三个按钮点击后选择对应的子控制器,看一下代码。

    #import "ViewController.h"
    #import "JJChildVCOne.h"
    #import "JJChildVCTwo.h"
    #import "JJChildVCThree.h"
    
    #define kViewControllerScreenWidth     [UIScreen mainScreen].bounds.size.width
    #define kViewControllerScreenHeight    [UIScreen mainScreen].bounds.size.height
    
    @interface ViewController ()
    
    @property (nonatomic, strong) UIViewController *currentVC;
    
    @end
    
    @implementation ViewController
    
    #pragma mark -  Override Base Function
    
    - (void)viewDidLoad
    {
        [super viewDidLoad];
        
        self.view.backgroundColor = [UIColor whiteColor];
        
        //设置UI
        [self setupUI];
        
        //加子控制器
        [self setupChildVC];
    }
    
    #pragma mark -  Object Private Function
    
    - (void)setupChildVC
    {
        JJChildVCOne *childOneVC = [[JJChildVCOne alloc] init];
        childOneVC.view.backgroundColor = [UIColor redColor];
        
        JJChildVCTwo *childTwoVC = [[JJChildVCTwo alloc] init];
        childTwoVC.view.backgroundColor = [UIColor blueColor];
        
        JJChildVCThree *childThreeVC = [[JJChildVCThree alloc] init];
        childThreeVC.view.backgroundColor = [UIColor greenColor];
        
        [self addChildViewController:childOneVC];
        [self addChildViewController:childTwoVC];
        [self addChildViewController:childThreeVC];
    }
    
    - (void)setupUI
    {
        for (NSInteger i = 0; i < 3; i ++) {
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            NSString *title = [NSString stringWithFormat:@"切换%d", i];
            [button setTitle:title forState:UIControlStateNormal];
            button.tag = i;
            [button addTarget:self action:@selector(buttonDidClick:) forControlEvents:UIControlEventTouchUpInside];
            button.titleLabel.font = [UIFont boldSystemFontOfSize:20.0];
            
            //不同标签的差异化设置
            if (i == 0) {
                button.backgroundColor = [UIColor redColor];
            }
            else if (i == 1){
                button.backgroundColor = [UIColor blueColor];
            }
            else {
                button.backgroundColor = [UIColor greenColor];
            }
            
            [self.view addSubview:button];
            button.frame = CGRectMake(i * kViewControllerScreenWidth / 3, 0.0, kViewControllerScreenWidth / 3, 40);
        }
    }
    
    #pragma mark -  Action && Notification
    
    - (void)buttonDidClick:(UIButton *)button
    {
        UIViewController *vc = self.childViewControllers[button.tag];
        vc.view.frame = CGRectMake(0.0, 40.0, kViewControllerScreenWidth, kViewControllerScreenHeight - 40.0);
        //移除掉当前显示的控制器的view
        [self.currentVC.view removeFromSuperview];
        self.currentVC = vc;
        //把选中的控制器view显示到界面上
        [self.view addSubview:self.currentVC.view];
    }
    
    @end
    

    下面看一下效果图

    后记

    未完,待续~~~

    相关文章

      网友评论

        本文标题: 父子控制器详细解析(一)

        本文链接:https://www.haomeiwen.com/subject/ptpdextx.html