iOS Child View Controller基礎使用

其實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];

參考資料:
https://developer.apple.com/library/archive/featuredarticles/ViewControllerPGforiPhoneOS/ImplementingaContainerViewController.html

這個是官方的文檔,有哪些細節不懂的可以看看。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。