How to find topmost view controller on iOS

后端 未结 30 2382
遥遥无期
遥遥无期 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条回答
  •  旧时难觅i
    2020-11-22 09:19

    Here is my take on this. Thanks to @Stakenborg for pointing out the way to skip getting UIAlertView as the top most controller

    -(UIWindow *) returnWindowWithWindowLevelNormal
    {
        NSArray *windows = [UIApplication sharedApplication].windows;
        for(UIWindow *topWindow in windows)
        {
            if (topWindow.windowLevel == UIWindowLevelNormal)
                return topWindow;
        }
        return [UIApplication sharedApplication].keyWindow;
    }
    
    -(UIViewController *) getTopMostController
    {
        UIWindow *topWindow = [UIApplication sharedApplication].keyWindow;
        if (topWindow.windowLevel != UIWindowLevelNormal)
        {
            topWindow = [self returnWindowWithWindowLevelNormal];
        }
    
        UIViewController *topController = topWindow.rootViewController;
        if(topController == nil)
        {
            topWindow = [UIApplication sharedApplication].delegate.window;
            if (topWindow.windowLevel != UIWindowLevelNormal)
            {
                topWindow = [self returnWindowWithWindowLevelNormal];
            }
            topController = topWindow.rootViewController;
        }
    
        while(topController.presentedViewController)
        {
            topController = topController.presentedViewController;
        }
    
        if([topController isKindOfClass:[UINavigationController class]])
        {
            UINavigationController *nav = (UINavigationController*)topController;
            topController = [nav.viewControllers lastObject];
    
            while(topController.presentedViewController)
            {
                topController = topController.presentedViewController;
            }
        }
    
        return topController;
    }
    

提交回复
热议问题