How to find topmost view controller on iOS

后端 未结 30 2835
遥遥无期
遥遥无期 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:02

    I think you need a combination of the accepted answer and @fishstix's

    + (UIViewController*) topMostController
    {
        UIViewController *topController = [UIApplication sharedApplication].keyWindow.rootViewController;
    
        while (topController.presentedViewController) {
            topController = topController.presentedViewController;
        }
    
        return topController;
    }
    

    Swift 3.0+

    func topMostController() -> UIViewController? {
        guard let window = UIApplication.shared.keyWindow, let rootViewController = window.rootViewController else {
            return nil
        }
    
        var topController = rootViewController
    
        while let newTopController = topController.presentedViewController {
            topController = newTopController
        }
    
        return topController
    }
    

提交回复
热议问题