其实ChildViewController的基本使用不是很复杂,主要就是添加、移除,切换也 是基于 添加、移除的相关方法的,但是建议一定要遵循官方要求,避免出现难以预料的bug。 在平时项目中的使用往往比这复杂的多,如果添加很多的childVC,移除的时机一定要把握好。
一.如何添加childViewController

官方说明如何添加
代码示例
//添加子控制器 该方法调用了willMoveToParentViewController:方法
[self addChildViewController:self.currentVC];
//设置子控制器视图的位置及大小,保证自控制器视图的正常显示
self.currentVC.view.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height-49);
//将子控制器视图添加到容器控制器的视图中
[self.view addSubview:_currentVC.view];
//需要显示调用
[_currentVC didMoveToParentViewController:self];
试验发现不调用didMoveToParentViewController方法也可以添加childVC成功,但是为了稳妥,推荐大家还是遵循苹果的要求,避免出现bug。
二.如何移除childViewController

官方说明如何移除
代码示例:
- (void) hideContentController: (UIViewController*) content {
//准备移除
[content willMoveToParentViewController:nil];
[content.view removeFromSuperview];
//确定移除 该方法会显示调用didMoveToParentViewController:nil
[content removeFromParentViewController];
}
三.如何切换childViewController
第一种:使用动画效果切换
[oldVC willMoveToParentViewController:nil];
[self addChildViewController:newVC];
//写这个是为了实现frame变化的动画的,要根据动画效果编码
newVC.view.frame = CGRectMake(0, 0, 0, 0);
//使用该方法做切换动画 使用该方法切换childVC的时候不需要add和remove 视图view
[self transitionFromViewController: oldVC toViewController: newVC
duration: 0.25 options:0
animations:^{
//实现视图拉伸的动画
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];
}];
第二种:不适用动画效果切换
[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];
这个是官方的文档,有哪些细节不懂的可以看看。