iOS 获取当前正在显示的controller

有时我们会有在一个view里弹出控制器的需要。这时就要获取当正在显示的controller。在网上也看到了一些做法,但是如果当前控制器是以模态的方式弹出的就获取不到。下面这种是以递归的方式获取

- (UIViewController *)topViewController {
    UIViewController *resultVC;
    resultVC = [self _topViewController:[[UIApplication sharedApplication].keyWindow rootViewController]];
    while (resultVC.presentedViewController) {
        resultVC = [self _topViewController:resultVC.presentedViewController];
    }
    return resultVC;
}
- (UIViewController *)_topViewController:(UIViewController *)vc {
    if ([vc isKindOfClass:[UINavigationController class]]) {
        return [self _topViewController:[(UINavigationController *)vc topViewController]];
    } else if ([vc isKindOfClass:[UITabBarController class]]) {
        return [self _topViewController:[(UITabBarController *)vc selectedViewController]];
    } else {
        return vc;
    }
    return nil;
}

用法:
[self topViewController]

你可能感兴趣的:(iOS 获取当前正在显示的controller)