获取当前显示的ViewController

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

一般我用

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

[objc]  view plain copy
  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 ([vcCurrent isKindOfClass:[UITabBarController class]]) {

            UITabBarController * vcTabBar = (UITabBarController *)vcCurrent;

            NSArray * arrVCS = [vcTabBar viewControllers];

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

            [vcNav pushViewController:vcNext animated:YES];

        }else{

            [vcCurrent.navigationController pushViewController:vcNext animated:YES];

        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值