父子控制器詳細(xì)解析(一)

版本記錄

版本號(hào) 時(shí)間
V1.0 2017.09.25

前言

在APP中很多時(shí)候我們都需要用到父子控制器來達(dá)到我們的需求瘦陈,這個(gè)用的次數(shù)不是很頻繁紧卒,但是在大的項(xiàng)目中搭建架構(gòu)的時(shí)候還是會(huì)用到的质蕉,接下來我們就詳細(xì)的解析一下父子控制器蔓同。相關(guān)代碼已發(fā)到 Github - 刀客傳奇

幾個(gè)基本概念

1. 定義

父子控制器涮拗,指的是一個(gè)控制器通過addChildViewController:方法添加多個(gè)控制器乾戏,被添加的控制器稱為子控制器迂苛,添加多個(gè)子控制器的控制器稱為父控制器。

2. 父子控制器關(guān)系

  • 父控制器處理的事件會(huì)自動(dòng)傳遞給子控制器鼓择。
  • 子控制器處理的事件會(huì)自動(dòng)傳給父控制器三幻。
  • 子控制器可以通過屬性parentViewController獲取父控制器 。
  • 父控制器可以通過屬性childViewControllers獲取所有子控制器呐能。
  • A控制器添加到B控制器上后念搬,A控制器就會(huì)被強(qiáng)引用,即使A控制器的view不正在顯示摆出,A控制器和A控制器的view都不會(huì)被銷毀朗徊。

3. 什么時(shí)候使用父子控制器?

當(dāng)Apple提供的框架不能滿足開發(fā)者的時(shí)候偎漫,考慮重新搭建框架爷恳。比如UITabBarControllertabBar默認(rèn)是在底部,想要把它放到頂部或者左邊象踊,實(shí)現(xiàn)起來會(huì)很困難温亲,這時(shí)考慮到模仿UITabBarController的功能,搭建新的框架可能會(huì)更簡單杯矩。

4. 創(chuàng)建父子控制器方法

一個(gè)控制器使用addChildViewController:方法添加子控制器栈虚。

如果兩個(gè)控制器的視圖View是父子關(guān)系,那么這兩個(gè)控制器也應(yīng)該是父子關(guān)系菊碟,也就是說應(yīng)該利用代碼創(chuàng)建父子關(guān)系节芥。

5. 父子控制器優(yōu)點(diǎn)和注意事項(xiàng)

  • 當(dāng)父控制器發(fā)生一些重大的事件,可以通知到子控制器逆害,比如說屏幕旋轉(zhuǎn)头镊。

  • 不要自己創(chuàng)建數(shù)組來管理子控制器,用 UIViewController 自帶的 childViewControllers 數(shù)組可以避免掉很多不必要的麻煩魄幕。

  • 可以在整體布局中嵌套一個(gè)scrollview相艇,使子控制器可以進(jìn)行滑動(dòng)切換,實(shí)現(xiàn)類似網(wǎng)易新聞和今日頭條不同頻道加載的效果纯陨。

6. 父子控制器的接口及幾個(gè)重要方法

下面我們要看一下父子控制器需要的幾個(gè)重要方法坛芽。

  • addChildViewController添加子控制器,建立父子關(guān)系
    • 如果重寫此方法翼抠,必須在實(shí)現(xiàn)中調(diào)用父類實(shí)現(xiàn)
    • 調(diào)用addChildViewController:會(huì)自動(dòng)調(diào)用child的willMoveToParentViewController:方法咙轩,不會(huì)自動(dòng)調(diào)用didMoveToParentViewController方法;
    • 如果childController已經(jīng)有一個(gè)不同的父控制器阴颖,那么它將首先通過調(diào)用removeFromParentViewController從當(dāng)前的父控制器移除活喊。
    • 如果一個(gè)父控制器的內(nèi)容中包含了另一個(gè)控制器的view,那么父子控制器的關(guān)系是必要的.
/*
  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從父控制器中移除子控制器
    • 將控制器從父控制器的子控制器數(shù)組中移除量愧;如果重寫此方法钾菊,必須在實(shí)現(xiàn)中調(diào)用父類實(shí)現(xiàn)帅矗。
/*
  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將要添加到父控制器。

    • 此方法會(huì)在視圖控制器被添加或移除之前調(diào)用煞烫。
    • 自定義容器類控制器在調(diào)用child的removeFromParentViewController方法前浑此,必須先調(diào)用child的willMoveToParentViewController:nil方法;
    • 如果重寫此方法滞详,必須在實(shí)現(xiàn)中調(diào)用父類實(shí)現(xiàn)凛俱;
    • 將要從parent移除時(shí),參數(shù)傳遞nil茵宪,將要添加到parent時(shí)最冰,參數(shù)傳父控制器;調(diào)用addChildViewController:會(huì)自動(dòng)調(diào)用child的willMoveToParentViewController:方法稀火,但不會(huì)自動(dòng)調(diào)用didMoveToParentViewController方法暖哨,可以在子控制器過渡完成時(shí)手動(dòng)調(diào)用didMoveToParentViewController,或者在沒有過渡效果時(shí)直接手動(dòng)調(diào)用didMoveToParentViewController凰狞;同樣的篇裁,removeFromParentViewController方法不會(huì)自動(dòng)調(diào)用[self willMoveToParentViewController:nil]而需要我們手動(dòng)進(jìn)行調(diào)用,但會(huì)自動(dòng)調(diào)用didMoveToParentViewController方法赡若。
  • didMoveToParentViewController添加到父控制器

    • 此方法會(huì)在視圖控制器被添加或移除之后調(diào)用达布;
    • 自定義容器類控制器在調(diào)用addChildViewController方法之后,必須調(diào)用child的didMoveToParentViewController:parent方法逾冬,如果有過渡過程黍聂,需要在過渡完成之后調(diào)用,否則直接調(diào)用身腻;
    • 如果重寫此方法产还,必須在實(shí)現(xiàn)中調(diào)用父類實(shí)現(xiàn);
/*
  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控制器轉(zhuǎn)場(chǎng)
    • 此方法用于在不同的子控制器之間過渡。
    • 過渡完成時(shí)嘀趟,toViewController的view將被添加到fromViewController的view的父視圖上脐区,fromViewController的view將被從父視圖上移除;
    • 對(duì)于iOS本來的容器類控制器例如導(dǎo)航控制器與TabbarController她按,請(qǐng)不要調(diào)用此方法牛隅;
      也可以直接用UIView的API,但是要確保酌泰,在fromViewController的view移除時(shí)toViewController的view已經(jīng)被添加到了視圖層級(jí)中媒佣;
    • 此方法底層中實(shí)現(xiàn)的順序是:添加toViewController的view,執(zhí)行動(dòng)畫陵刹,動(dòng)畫完成時(shí)移除fromViewController的view丈攒;
    • 如果重寫此方法,必須在實(shí)現(xiàn)中調(diào)用父類實(shí)現(xiàn)授霸。
/*
  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);

一個(gè)簡單實(shí)例

下面我們就看一個(gè)簡單實(shí)例巡验,三個(gè)按鈕點(diǎn)擊后選擇對(duì)應(yīng)的子控制器,看一下代碼碘耳。

#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];
    
    //設(shè)置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];
        
        //不同標(biāo)簽的差異化設(shè)置
        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);
    //移除掉當(dāng)前顯示的控制器的view
    [self.currentVC.view removeFromSuperview];
    self.currentVC = vc;
    //把選中的控制器view顯示到界面上
    [self.view addSubview:self.currentVC.view];
}

@end

下面看一下效果圖

后記

未完显设,待續(xù)~~~

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市辛辨,隨后出現(xiàn)的幾起案子捕捂,更是在濱河造成了極大的恐慌,老刑警劉巖斗搞,帶你破解...
    沈念sama閱讀 218,284評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件指攒,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡僻焚,警方通過查閱死者的電腦和手機(jī)允悦,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,115評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來虑啤,“玉大人隙弛,你說我怎么就攤上這事∧剑” “怎么了全闷?”我有些...
    開封第一講書人閱讀 164,614評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長萍启。 經(jīng)常有香客問我总珠,道長,這世上最難降的妖魔是什么勘纯? 我笑而不...
    開封第一講書人閱讀 58,671評(píng)論 1 293
  • 正文 為了忘掉前任局服,我火速辦了婚禮,結(jié)果婚禮上屡律,老公的妹妹穿的比我還像新娘腌逢。我一直安慰自己,他們只是感情好超埋,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,699評(píng)論 6 392
  • 文/花漫 我一把揭開白布搏讶。 她就那樣靜靜地躺著,像睡著了一般霍殴。 火紅的嫁衣襯著肌膚如雪媒惕。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,562評(píng)論 1 305
  • 那天来庭,我揣著相機(jī)與錄音妒蔚,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛肴盏,可吹牛的內(nèi)容都是我干的科盛。 我是一名探鬼主播,決...
    沈念sama閱讀 40,309評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼菜皂,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼贞绵!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起恍飘,我...
    開封第一講書人閱讀 39,223評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤榨崩,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后章母,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體母蛛,經(jīng)...
    沈念sama閱讀 45,668評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,859評(píng)論 3 336
  • 正文 我和宋清朗相戀三年乳怎,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了彩郊。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,981評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡舞肆,死狀恐怖焦辅,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情椿胯,我是刑警寧澤筷登,帶...
    沈念sama閱讀 35,705評(píng)論 5 347
  • 正文 年R本政府宣布,位于F島的核電站哩盲,受9級(jí)特大地震影響前方,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜廉油,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,310評(píng)論 3 330
  • 文/蒙蒙 一惠险、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧抒线,春花似錦班巩、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,904評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至眨猎,卻和暖如春抑进,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背睡陪。 一陣腳步聲響...
    開封第一講書人閱讀 33,023評(píng)論 1 270
  • 我被黑心中介騙來泰國打工寺渗, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留匿情,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,146評(píng)論 3 370
  • 正文 我出身青樓信殊,卻偏偏與公主長得像炬称,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子鸡号,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,933評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容