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

版本记录

版本号 时间
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

下面看一下效果图

后记

未完,待续~~~

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,271评论 5 466
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,725评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,252评论 0 328
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,634评论 1 270
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,549评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 47,985评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,471评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,128评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,257评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,233评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,235评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,940评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,528评论 3 302
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,623评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,858评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,245评论 2 344
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,790评论 2 339

推荐阅读更多精彩内容