1. 程式人生 > >iOS連續dismiss幾個ViewController的方法

iOS連續dismiss幾個ViewController的方法

操作 lag boa 控制 oid -o appear article 繼承

原文鏈接:http://blog.csdn.net/longshihua/article/details/51282388

presentViewController是經常會用到的展現ViewController的方式,而顯示和去除presentViewController也是很簡單的,主要是下面兩個方法:

- (void)presentViewController:(UIViewController *)viewControllerToPresent animated: (BOOL)flag completion:(void (^ __nullable)(void))completionNS_AVAILABLE_IOS(5_0);

- (void)dismissViewControllerAnimated: (BOOL)flag completion: (void (^__nullable)(void))completionNS_AVAILABLE_IOS(5_0);

但是有的時候我們的需求很特殊,比如在一個presentViewController裏要present另一個viewController,甚至再present一個viewController,然後可能在某個時候APP發出一條消息,需要一下子dismiss掉所有的viewController,回到最開始的視圖控制器,這時候該如何辦呢?下面一起來看看解決辦法?

首先,必須知道現在整個APP最頂層的ViewController是哪個,我的做法是建立一個父視圖控制器,稱為BaseViewController,然後在該視圖控制器的viewWillAppear進行記錄操作,使用視圖控制器的presentingViewController屬性記錄當前視圖控制器,然後對於需要進行present操作的視圖控制器,繼承於BaseViewController,那麽每次present一個新的視圖控制器,父視圖控制器的viewWillAppear方法都會被執行:

-(void)viewWillAppear:(BOOL)animated{  
  
    AppDelegate 
*delegate=(AppDelegate *)[[UIApplication sharedApplication]delegate]; delegate.presentingController = self; }


最後,在需要處理時間的地方(如:點擊事件),在點擊事件的方法中加入如下代碼,即可回到最初視圖控制器顯示頁面:

- (void)clickButton:(id)sender {  
      
    AppDelegate *delegate=(AppDelegate *)[[UIApplicationsharedApplication]delegate];  
    
    if (delegate.presentingController)  
    {  
        UIViewController *vc =self.presentingViewController;  
  
        if ( !vc.presentingViewController )   return;  
          
        //循環獲取present出來本視圖控制器的視圖控制器(簡單一點理解就是上級視圖控制器),一直到最底層,然後在dismiss,那麽就ok了!  
        while (vc.presentingViewController)  
        {  
            vc = vc.presentingViewController;  
        }  
          
        [vc dismissViewControllerAnimated:YEScompletion:^{  
              
        }];  
    }  
} 


屬性解析:

presentedViewController:The view controller that is presented by this view controlller(read-only),被本視圖控制器present出來的的視圖控制器(只讀)

presentingViewController:The view controller that presented this view controller. (read-only),present出來本視圖控制器的視圖控制器(只讀)

iOS連續dismiss幾個ViewController的方法