获取最顶层的ViewController

谁都会走 提交于 2020-02-26 11:58:46
// 获取最顶层的ViewController
[self getCurrentVC1];



//获取当前屏幕显示的viewcontroller
- (UIViewController *)getCurrentVC1
{
     UIViewController *rootViewController = [self getViewControllerWindow].rootViewController;
     UIViewController *currentVC = [self getCurrentVCFrom:rootViewController];
     return currentVC;
}

//获取RootViewController所在的window
- (UIWindow*)getViewControllerWindow{
     UIWindow *window = [UIApplication sharedApplication].delegate.window;
     if (window.windowLevel != UIWindowLevelNormal) {
          NSArray *windows = [UIApplication sharedApplication].windows;
          for (UIWindow *target in windows) {
               if (target.windowLevel == UIWindowLevelNormal) {
                    window = target;
                    break;
               }
          }
     }
     return window;
}

- (UIViewController *)getCurrentVCFrom:(UIViewController *)rootVC
{
     UIViewController *currentVC;
     
     if ([rootVC presentedViewController]) {
          // 视图是被presented出来的
          while ([rootVC presentedViewController]) {
               rootVC = [rootVC presentedViewController];
          }
     }
     
     if ([rootVC isKindOfClass:[UITabBarController class]]) {
          // 根视图为UITabBarController
          currentVC = [self getCurrentVCFrom:[(UITabBarController *)rootVC selectedViewController]];
     } else if ([rootVC isKindOfClass:[UINavigationController class]]){
          // 根视图为UINavigationController
          currentVC = [self getCurrentVCFrom:[(UINavigationController *)rootVC visibleViewController]];
     } else {
          // 根视图为非导航类
          currentVC = rootVC;
          
     }
     
     return currentVC;
}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!