获取当前显示的ViewController

来源:互联网 发布:erp企业管理系统源码 编辑:程序博客网 时间:2024/06/06 11:45

我们在非视图类中想要随时展示一个view时,需要将被展示的view加到当前view的子视图,或用当前view presentViewController,或pushViewContrller,这些操作都需要获取当前正在显示的ViewController。

一般我用

 UIViewController * vcCurrent =[[UIApplicationsharedApplication]keyWindow].currentViewController;就可以了,但是在网上看到了下面这种方法,应该是比上面更严谨些,但是现在还没遇到展现她的特别作用的时候,不过也贴出来,说不定以后会用到。

[objc] view plaincopy
  1. //获取当前屏幕显示的viewcontroller  
  2. - (UIViewController *)getCurrentVC  
  3. {  
  4.     UIViewController *result = nil;  
  5.       
  6.     UIWindow * window = [[UIApplication sharedApplication] keyWindow];  
  7.     if (window.windowLevel != UIWindowLevelNormal)  
  8.     {  
  9.         NSArray *windows = [[UIApplication sharedApplication] windows];  
  10.         for(UIWindow * tmpWin in windows)  
  11.         {  
  12.             if (tmpWin.windowLevel == UIWindowLevelNormal)  
  13.             {  
  14.                 window = tmpWin;  
  15.                 break;  
  16.             }  
  17.         }  
  18.     }  
  19.       
  20.     UIView *frontView = [[window subviews] objectAtIndex:0];  
  21.     id nextResponder = [frontView nextResponder];  
  22.       
  23.     if ([nextResponder isKindOfClass:[UIViewController class]])  
  24.         result = nextResponder;  
  25.     else  
  26.         result = window.rootViewController;  
  27.       
  28.     return result;  
  29. }  
当获取当前ViewController之后,判断这个vc本身是导航控制器,还是导航控制器的子VC,能不能直接用push方法

if ([vcCurrentisKindOfClass:[UITabBarControllerclass]]) {

           UITabBarController * vcTabBar = (UITabBarController *)vcCurrent;

           NSArray * arrVCS = [vcTabBar viewControllers];

           FMNavigationController * vcNav = [arrVCS objectAtIndex:vcTabBar.selectedIndex];

            [vcNavpushViewController:vcNext animated:YES];

        }else{

            [vcCurrent.navigationControllerpushViewController:vcNext animated:YES];

        }

0 0