How to find topmost view controller on iOS

后端 未结 30 2903
遥遥无期
遥遥无期 2020-11-22 08:40

I\'ve run into a couple of cases now where it would be convenient to be able to find the \"topmost\" view controller (the one responsible for the current view), but haven\'t

30条回答
  •  深忆病人
    2020-11-22 09:06

    Expanding on @Eric's answer, you need to be careful that the keyWindow is actually the window you want. If you are trying to utilize this method after tapping something in an alert view for example, the keyWindow will actually be the alert's window, and that will cause problems for you no doubt. This happened to me in the wild when handling deep links via an alert and caused SIGABRTs with NO STACK TRACE. Total bitch to debug.

    Here's the code I'm using now:

    - (UIViewController *)getTopMostViewController {
        UIWindow *topWindow = [UIApplication sharedApplication].keyWindow;
        if (topWindow.windowLevel != UIWindowLevelNormal) {
            NSArray *windows = [UIApplication sharedApplication].windows;
            for(topWindow in windows)
            {
                if (topWindow.windowLevel == UIWindowLevelNormal)
                    break;
            }
        }
    
        UIViewController *topViewController = topWindow.rootViewController;
    
        while (topViewController.presentedViewController) {
            topViewController = topViewController.presentedViewController;
        }
    
        return topViewController;
    }
    

    Feel free to mix this with whatever flavor of retrieving the top view controller you like from the other answers on this question.

提交回复
热议问题