兩個(gè)ViewController 之間的父子關(guān)系模式
- 父VC:parent ViewController乍楚,以下簡(jiǎn)稱pVC
- 子VC:child ViewController驴一,以下簡(jiǎn)稱cVC
綜述
實(shí)現(xiàn)一個(gè)Custom Container View Controller并不是一個(gè)簡(jiǎn)單的事情灾梦,主要分為兩個(gè)階段:父子關(guān)系的建立以及父子關(guān)系的解除。如果pVC將cVC的view添加為自己的subview到千,那么cVC必須為pVC的Child View Controller包晰,
另一些如navigation 或 tabbar 尝艘,不是通過(guò)上面的這種方式建立關(guān)系演侯。
比如UINavigationController,一個(gè)View Controller被push進(jìn)來(lái)后便和navigationController建立父子關(guān)系了,但是只有最上面的View Controller 是顯示著的背亥,底下的View Controller的view則被移出了容器的view的顯示層級(jí)秒际,當(dāng)一個(gè)View Controller被pop之后,便和navigationController解除了父子關(guān)系了狡汉。
下面來(lái)介紹以下建立/解除 VC之間父子關(guān)系
建立
假設(shè) cVC是下面代碼中的self.centerViewController
- addChildViewController:接口建立了邏輯上的父子關(guān)系娄徊,子可以通過(guò)
.parentViewController
,訪問(wèn)其pVC盾戴,addChildViewController:接口的邏輯中會(huì)自動(dòng)調(diào)用[content willMoveToParentViewController:self]
; - 建立父子關(guān)系后寄锐,便是將cVC的view加入到pVC的view hierarchy上,同時(shí)要決定的是 content的view顯示的區(qū)域范圍。此時(shí)pVC只是一個(gè)容器橄仆,cVC占據(jù)了他的邊界
- 調(diào)用child的 didMoveToParentViewController: 剩膘,以通知child,完成了父子關(guān)系的建立 這步操作很重要E韫恕怠褐!
[self addChildViewController:self.centerViewController];
self.centerViewController.view.frame = self.view.bounds;
[self.view addSubview:self.centerViewController.view];
[self.centerViewController didMoveToParentViewController:self];
解除
- 通知child,即將解除父子關(guān)系您宪,從語(yǔ)義上也可以看出 child的parent即將為nil
- 將child的view從父VC的view的hierarchy中移除
- 通過(guò)removeFromParentViewController的調(diào)用真正的解除關(guān)系奈懒,
removeFromParentViewController
會(huì)自動(dòng)調(diào)用[content didMoveToParentViewController:nil]
[content willMoveToParentViewController:nil]; //1
[content.view removeFromSuperview]; //2
[content removeFromParentViewController]; //3
最后附上一個(gè)總結(jié)表:
函數(shù)名 | 執(zhí)行方 | AUTO / Manual |
---|---|---|
willMoveToParentViewController | cVC 執(zhí)行 | AUTO |
addChildViewController | pVC執(zhí)行 | MANUAL |
didMoveToParentViewController | cVC 執(zhí)行 | MANUAL |
willMoveToParentViewController | cVC執(zhí)行 | MANUAL |
removeFromParentViewController | pVCt執(zhí)行 | MANUAL |
didMoveToParentViewController | cVC執(zhí)行 | AUTO |