How to find topmost view controller on iOS

后端 未结 30 2379
遥遥无期
遥遥无期 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 08:57

    This is an improvement to Eric's answer:

    UIViewController *_topMostController(UIViewController *cont) {
        UIViewController *topController = cont;
    
        while (topController.presentedViewController) {
            topController = topController.presentedViewController;
        }
    
        if ([topController isKindOfClass:[UINavigationController class]]) {
            UIViewController *visible = ((UINavigationController *)topController).visibleViewController;
            if (visible) {
                topController = visible;
            }
        }
    
        return (topController != cont ? topController : nil);
    }
    
    UIViewController *topMostController() {
        UIViewController *topController = [UIApplication sharedApplication].keyWindow.rootViewController;
    
        UIViewController *next = nil;
    
        while ((next = _topMostController(topController)) != nil) {
            topController = next;
        }
    
        return topController;
    }
    

    _topMostController(UIViewController *cont) is a helper function.

    Now all you need to do is call topMostController() and the top most UIViewController should be returned!

提交回复
热议问题