其實(shí)ChildViewController的基本使用不是很復(fù)雜展氓,主要就是添加捆愁、移除割去,切換也 是基于 添加、移除的相關(guān)方法的昼丑,但是建議一定要遵循官方要求呻逆,避免出現(xiàn)難以預(yù)料的bug。 在平時(shí)項(xiàng)目中的使用往往比這復(fù)雜的多菩帝,如果添加很多的childVC页慷,移除的時(shí)機(jī)一定要把握好。
一.如何添加childViewController
官方說(shuō)明如何添加
代碼示例
//添加子控制器 該方法調(diào)用了willMoveToParentViewController:方法
[self addChildViewController:self.currentVC];
//設(shè)置子控制器視圖的位置及大小胁附,保證自控制器視圖的正常顯示
self.currentVC.view.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height-49);
//將子控制器視圖添加到容器控制器的視圖中
[self.view addSubview:_currentVC.view];
//需要顯示調(diào)用
[_currentVC didMoveToParentViewController:self];
試驗(yàn)發(fā)現(xiàn)不調(diào)用didMoveToParentViewController方法也可以添加childVC成功酒繁,但是為了穩(wěn)妥,推薦大家還是遵循蘋果的要求控妻,避免出現(xiàn)bug州袒。
二.如何移除childViewController
官方說(shuō)明如何移除
代碼示例:
- (void) hideContentController: (UIViewController*) content {
//準(zhǔn)備移除
[content willMoveToParentViewController:nil];
[content.view removeFromSuperview];
//確定移除 該方法會(huì)顯示調(diào)用didMoveToParentViewController:nil
[content removeFromParentViewController];
}
三.如何切換childViewController
第一種:使用動(dòng)畫效果切換
[oldVC willMoveToParentViewController:nil];
[self addChildViewController:newVC];
//寫這個(gè)是為了實(shí)現(xiàn)frame變化的動(dòng)畫的,要根據(jù)動(dòng)畫效果編碼
newVC.view.frame = CGRectMake(0, 0, 0, 0);
//使用該方法做切換動(dòng)畫 使用該方法切換childVC的時(shí)候不需要add和remove 視圖view
[self transitionFromViewController: oldVC toViewController: newVC
duration: 0.25 options:0
animations:^{
//實(shí)現(xiàn)視圖拉伸的動(dòng)畫
oldVC.view.frame = CGRectMake(0, 0, 0, 0);
newVC.view.frame = oldVC.view.frame;
}
completion:^(BOOL finished) {
// Remove the old view controller and send the final
// notification to the new view controller.
[oldVC removeFromParentViewController];
[newVC didMoveToParentViewController:self];
}];
第二種:不適用動(dòng)畫效果切換
[oldVC willMoveToParentViewController:nil];
[self addChildViewController:newVC];
newVC.view.frame = oldVC.view.frame;
[self.view addSubview:newVC.view];
[oldVC removeFromParentViewController];
[oldVC.view removeFromSuperview];
[newVC didMoveToParentViewController:self];
這個(gè)是官方的文檔弓候,有哪些細(xì)節(jié)不懂的可以看看郎哭。