获取Screen最顶层的ViewController

840 阅读1分钟

图片来自网络

图片来自网络

在App内的任何地方:

//获取当前屏幕 显示的viewcontroller
- (UIViewController *)getCurrentVC
{
    UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    UIViewController *currentVC = [self getCurrentVCFromRootVC:rootViewController];
    return currentVC;
}

- (UIViewController *) getCurrentVCFromRootVC:(UIViewController *)rootVC
{
    UIViewController *currentVC;

    if ([rootVC presentedViewController]) {
        // 视图是被presented出来的       
        rootVC = [rootVC presentedViewController];
    }

    if ([rootVC isKindOfClass:[UITabBarController class]]) {
        // 根视图是:UITabBarController     
        currentVC = [self getCurrentVCFromRootVC:[(UITabBarController *)rootVC selectedViewController]];
    } else if ([rootVC isKindOfClass:[UINavigationController class]]){
        // 根视图是:UINavigationController
        currentVC = [self getCurrentVCFromRootVC:[(UINavigationController *)rootVC visibleViewController]];
    } else {
        // 根视图是:非导航类、非标签类
        currentVC = rootVC;
    }

    return currentVC;
}

方法的使用

UIViewController *topVC = [self getCurrentVC];

由于是AppDelegate单例类的原因,在其他任何地方都可以添加使用 上述方法

当然我们也可以单独为“AppDelegate添加方法 或 添加类别,之后直接调用 就可以了!可提高代码的复用性,简化代码量!

2017.11.03

goyohol's essay