iOS获取屏幕最上层的ViewController

实际开发中,时长需要获取屏幕最上层的ViewController,以下代码是对实现此需求的简单代码封装。

PS:以下代码被封装为UIApplication类的分类


`
//获取rootViewController

  • (UIViewController )rootViewController{
    UIWindow
    window = [UIApplication sharedApplication].keyWindow;
    return window.rootViewController;
    }
    `


`
//获取Window当前显示的ViewController

  • (UIViewController)currentViewController{
    UIViewController
    vc = [UIApplication rootViewController];

    while (1) {
    if ([vc isKindOfClass:[UITabBarController class]]) {
    vc = ((UITabBarController*)vc).selectedViewController;
    }

      if ([vc isKindOfClass:[UINavigationController class]]) {
          vc = ((UINavigationController*)vc).visibleViewController;
      }
      
      if (vc.presentedViewController) {
          vc = vc.presentedViewController;
      }else{
          break;
      }
    

    }

    return vc;
    }

`

你可能感兴趣的:(iOS获取屏幕最上层的ViewController)