學(xué)習(xí)使用addChildViewController

ViewController有一個(gè)方法是addChildViewController,但是,我并不知道如何的管理這個(gè)添加上去的子類Controller。所以查找了資料,學(xué)習(xí)了他的一些相關(guān)方法,在這里做些簡單的介紹。
首先是介紹添加Controller:

    TowController *towCol = [[TowController alloc]init];
    towCol.view.frame = self.view.bounds;
    [self addChildViewController:towCol];//1
    [self.view addSubview:towCol.view];//2
    [towCol didMoveToParentViewController:self];//3

1.將towCol添加到Controller的childViewController,建立父子關(guān)系??梢酝ㄟ^parentViewController訪問towCol的父類,調(diào)用addChildViewController方法系統(tǒng)會(huì)自動(dòng)調(diào)用willMoveToParentViewController:方法。
2.將towCol的view加到父類的view上去,當(dāng)然還要確定view在父類view上的frame。
3.調(diào)用child的 didMoveToParentViewController: ,以通知child,完成了父子關(guān)系的建立。

接著介紹移除一個(gè)Controller:

    [towCol willMoveToParentViewController:nil]; //1
    [towCol.view removeFromSuperview]; //2
    [towCol removeFromParentViewController]; //3

1.通知child,即將解除父子關(guān)系,設(shè)置 child的parent即將為nil。
2.將child的view從父類的view中移除 。
3.通過removeFromParentViewController的調(diào)用真正的解除關(guān)系,removeFromParentViewController會(huì)自動(dòng)調(diào)用
[towCol didMoveToParentViewController:nil]。
這樣簡單的添加和移除的就ok了。

Controller里面的viewWillAppear:(BOOL)animated在subview真正加到父view之前調(diào)用,viewDidAppear:(BOOL)animated在真正被add到父view之后調(diào)用,視圖消失也是一樣。

[towCol beginAppearanceTransition:YES animated:YES]觸發(fā)towCol的viewWillAppear,[towCol beginAppearanceTransition:NO animated:YES]觸發(fā)towCol的viewWillDisappear,和他們配套的[towCol endAppearanceTransition]分別觸發(fā)viewDidAppear和viewDidDisappear
當(dāng)然還有視圖旋轉(zhuǎn)的方法在這里就不介紹了,可以自己去找資料。

初次接觸,我也只能了解這么多了,如果想要深入了解,可以自行查找資料。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容