定义: A container view controller contains content owned by other view controllers.
也就是说一个View Controller显示的某部分内容属于另一个View Controller,那么这个View Controller就是一个Container。
Container的主要职责就是管理一个或多个Child View Controller的展示的生命周期,需要传递显示以及旋转相关的回调。
其实显示或者旋转的回调的触发的源头来自于window,一个app首先有一个主window,初始化的时候需要给这个主window指定一个rootViewController,window会将显示相关的回调(viewWillAppear:, viewWillDisappear:, viewDidAppear:, or viewDidDisappear: )以及旋转相关的回调(willRotateToInterfaceOrientation:duration: ,willAnimateRotationToInterfaceOrientation:duration:,didRotateFromInterfaceOrientation:)传递给rootViewController。rootViewController需要再将这些callbacks的调用传递给它的Child View Controllers。
一. 父子关系范式
实现一个Custom Container View Controller并不是一个简单的事情,主要分为两个阶段:父子关系的建立以及父子关系的解除。
展示一个名为content的child view controller:
[self addChildViewController:content]; //1
content.view.frame = [self frameForContentController];
[self.view addSubview:self.currentClientView]; //2
[content didMoveToParentViewController:self]; //3
1.将content添加为child view controller,addChildViewController:接口建立了逻辑上的父子关系,子可以通过parentViewController,访问其父VC,addChildViewController:接口的逻辑中会自动调用 [content willMoveToParentViewController:self];
2.建立父子关系后,便是将content的view加入到父VC的view hierarchy上,同时要决定的是 content的view显示的区域范围。
3.调用child的 didMoveToParentViewController: ,以通知child,完成了父子关系的建立。
移除一个child view controller:
[content willMoveToParentViewController:nil]; //1
[content.view removeFromSuperview]; //2
[content removeFromParentViewController]; //3