Container ViewController初探1

今天调试程序遇到个问题,iOS7下在弹出Modal的子界面时,弹出层次不对,键盘和界面被分割在了Window的两侧,导致显示异常
Presenting view controllers on detached view controllers is discouraged <HSRootViewController: 0x15dd248b0>.
由于最上面的窗口是UIWindow,故考虑用addSubView的方式将ViewController.view添加上去了,自己维护ViewController的生存期就好了,但同时也发现了iOS很早就提供的ContainerViewController方式
特此记录下
https://developer.apple.com/library/ios/featuredarticles/ViewControllerPGforiPhoneOS/CreatingCustomContainerViewControllers/CreatingCustomContainerViewControllers.html

Adding and Removing a Child
Listing 14-1 shows a typical implementation that adds a view controller as a child of another view controller. Each numbered step in the listing is described in more detail following the listing.

Listing 14-1 Adding another view controller’s view to the container’s view hierarchy
- (void) displayContentController: (UIViewController*) content;
{
[self addChildViewController:content]; // 1
content.view.frame = [self frameForContentController]; // 2
[self.view addSubview:self.currentClientView];
[content didMoveToParentViewController:self]; // 3
}
Here’s what the code does:

It calls the container’s addChildViewController: method to add the child. Calling the addChildViewController: method also calls the child’s willMoveToParentViewController: method automatically.
It accesses the child’s view property to retrieve the view and adds it to its own view hierarchy. The container sets the child’s size and position before adding the view; containers always choose where the child’s content appears. Although this example does this by explicitly setting the frame, you could also use layout constraints to determine the view’s position.
It explicitly calls the child’s didMoveToParentViewController: method to signal that the operation is complete.
Eventually, you want to be able to remove the child’s view from the view hierarchy. In this case, shown in Listing 14-2, you perform the steps in reverse.

Listing 14-2 Removing another view controller’s view to the container’s view hierarchy
- (void) hideContentController: (UIViewController*) content
{
[content willMoveToParentViewController:nil]; // 1
[content.view removeFromSuperview]; // 2
[content removeFromParentViewController]; // 3
}

你可能感兴趣的:(controller)