Custom Container View Controller

定义: 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指定一个rootViewControllerwindow会将显示相关的回调(viewWillAppear:, viewWillDisappear:, viewDidAppear:, or viewDidDisappear: )以及旋转相关的回调(willRotateToInterfaceOrientation:duration:willAnimateRotationToInterfaceOrientation:duration:didRotateFromInterfaceOrientation:)传递给rootViewControllerrootViewController需要再将这些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 controlleraddChildViewController:接口建立了逻辑上的父子关系,子可以通过parentViewController,访问其父VC,addChildViewController:接口的逻辑中会自动调用 [content willMoveToParentViewController:self];

2.建立父子关系后,便是将contentview加入到父VC的view hierarchy上,同时要决定的是 content的view显示的区域范围。

3.调用childdidMoveToParentViewController: ,以通知child,完成了父子关系的建立。

移除一个child view controller:

[content willMoveToParentViewController:nil]; //1 
[content.view removeFromSuperview]; //2 
[content removeFromParentViewController]; //3 
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容