[IOS development 1] get the viewcontroller at the top of the current screen



During the development process, we sometimes need to obtain the top-level viewcontroller displayed on the current screen, and then operate this viewcontroller to realize some functions, such as adding a loading circle and a prompt box.


Search through the bottom viewcontroller in turn until the top viewcontroller is found, that is, from the rootviewcontroller of the keywindow of uiapplication (if there are multiple uiwindows, the selection of UIWindow should be considered.

In the process of searching, we should consider whether the current viewcontroller is uitabbarcontroller or UINavigationController, and whether the current viewcontroller passes throughpresentViewController:animated:completion:The mode shows the other viewcontrollers.


// UIViewController+TopViewController.h

+ (UIViewController * )topViewController {
    UIViewController *resultVC;
    resultVC = [self recursiveTopViewController:[[UIApplication sharedApplication].keyWindow rootViewController]];
    while (resultVC.presentedViewController) {
        resultVC = [self recursiveTopViewController:resultVC.presentedViewController];
    return resultVC;

+ (UIViewController * )recursiveTopViewController:(UIViewController *)vc {
    if ([vc isKindOfClass:[UINavigationController class]]) {
        return [self recursiveTopViewController:[(UINavigationController *)vc topViewController]];
    } else if ([vc isKindOfClass:[UITabBarController class]]) {
        return [self recursiveTopViewController:[(UITabBarController *)vc selectedViewController]];
    } else {
        return vc;
    return nil;


UIViewController *vc = [UIViewController toViewController];