一個控制器包含其餘一個或多個控制器,前者爲容器控制器 (Container View Controller),後者爲子控制器 (Child View Controller)。UINavigationController、UITabBarController 是經常使用的容器控制器。本文介紹自定義容器控制器的方法。html
- (void)displayContentController:(UIViewController *)content { [self addChildViewController:content]; content.view.frame = [self frameForContentController]; [self.view addSubview:self.currentClientView]; [content didMoveToParentViewController:self]; }
注意,容器控制器的 addChildViewController: 方法會調用子控制器的 willMoveToParentViewController: 方法,所以不須要寫子控制器的 willMoveToParentViewController: 方法。ios
- (void)hideContentController:(UIViewController *)content { [content willMoveToParentViewController:nil]; [content.view removeFromSuperview]; [content removeFromParentViewController]; }
注意,子控制器的 removeFromParentViewController 方法會調用 didMoveToParentViewController: 方法,不用寫 didMoveToParentViewController: 方法。git
- (void)cycleFromViewController:(UIViewController *)oldVC toViewController:(UIViewController *)newVC { // Prepare the two view controllers for the change. [oldVC willMoveToParentViewController:nil]; [self addChildViewController:newVC]; // Get the start frame of the new view controller and the end frame // for the old view controller. Both rectangles are offscreen. newVC.view.frame = [self newViewStartFrame]; CGRect endFrame = [self oldViewEndFrame]; // Queue up the transition animation. [self transitionFromViewController:oldVC toViewController:newVC duration:0.25 options:0 animations:^{ // Animate the views to their final positions. newVC.view.frame = oldVC.view.frame; oldVC.view.frame = endFrame; } completion:^(BOOL finished) { // Remove the old view controller and send the final // notification to the new view controller. [oldVC removeFromParentViewController]; [newVC didMoveToParentViewController:self]; }]; }
容器控制器的 transitionFromViewController:toViewController:duration:options:animations:completion: 方法將 newVC 的 view 添加進來,執行動畫 animations block,動畫結束就移除 oldVC 的 view。github
- (BOOL)shouldAutomaticallyForwardAppearanceMethods { return NO; }
若是加上這一句,容器控制器就要在子控制出現和消失時通知子控制器,分別經過調用子控制器的 beginAppearanceTransition:animated: 方法和 endAppearanceTransition() 方法實現,不要直接調用子控制器的 viewWillAppear:、viewDidAppear:、viewWillDisappear:、viewDidDisappear: 方法。app
重載 childViewControllerForStatusBarStyle 屬性,返回相應的子控制器,讓子控制器決定狀態欄樣式。當這個屬性發生變化,調用 setNeedsStatusBarAppearanceUpdate() 方法更新狀態欄樣式。ide
容器控制器能夠用子控制器的 preferredContentSize 屬性決定子控制器 view 的大小。動畫
https://github.com/ViewDeck/ViewDeck3d
左右側滑視圖,實現側滑菜單功能。code
https://github.com/Silence-GitHub/SWScrollViewControllerhtm
Scroll view 里加入子控制器的視圖,能左右滑動切換子控制器。
https://github.com/Silence-GitHub/SWSegmentedController
經過 UISegmentedControl 切換子控制器。
轉載請註明出處:http://www.cnblogs.com/silence-cnblogs/p/6370049.html