iOS 获取当前正在显示的ViewController

来源:互联网 发布:linux yum安装maven 编辑:程序博客网 时间:2024/05/21 15:08

http://blog.csdn.net/worldzhy/article/details/42120929


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


[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. }  



2.获取当前屏幕中present出来的viewcontroller。

[objc] view plain copy
  1. - (UIViewController *)getPresentedViewController  
  2. {  
  3.     UIViewController *appRootVC = [UIApplication sharedApplication].keyWindow.rootViewController;  
  4.     UIViewController *topVC = appRootVC;  
  5.     if (topVC.presentedViewController) {  
  6.         topVC = topVC.presentedViewController;  
  7.     }  
  8.       
  9.     return topVC;  
  10. }  

0 0
原创粉丝点击