美文网首页征服iOS
iOS获取屏幕最上层的ViewController

iOS获取屏幕最上层的ViewController

作者: KillSimon | 来源:发表于2016-06-12 11:41 被阅读0次

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

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

    <pre>
    `
    //获取rootViewController

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

    <pre>
    `
    //获取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;
      }

    `
    </pre>

    相关文章

      网友评论

        本文标题:iOS获取屏幕最上层的ViewController

        本文链接:https://www.haomeiwen.com/subject/oepedttx.html