ios - 如何在 iOS 上找到最顶层的 View Controller

标签 ios objective-c uiview uiviewcontroller uikit

我现在遇到了几种情况,可以很方便地找到“最顶层” View Controller (负责当前 View 的 Controller ),但还没有找到方法。

基本上挑战是这样的:鉴于一个在不是 View Controller 的类中执行(或 View )[和没有事件 View 的地址] 并且没有传递最顶层 View Controller 的地址(或者说,导航 Controller 的地址),是否有可能找到该 View Controller ? (如果是的话,怎么做?)

或者,如果做不到这一点,是否有可能找到最顶层的 View ?

最佳答案

我认为您需要将接受的答案和@fishstix 结合起来

+ (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
}

关于ios - 如何在 iOS 上找到最顶层的 View Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6131205/

相关文章:

ios - 如何用新数据刷新 UItableViewcell

ios - 如何在 UIImage 上方绘制文本以创建新图像

iphone - 如何将参数传递给此函数?

ios - 为什么当我删除 UIView subview 时我的 SurperView 没有响应?

ios - 获取 LLDB 断点中的方法名称和选择器

ios - iOS 上的套接字 connect() 阻塞超过 30 秒

ios - 无法将 UIViewController 限制为仅纵向

iphone - 从 plist 的数据加载给我错误顺序的值

ios - 从 Xib 加载的自定义 UIView

ios - 如何在 UIViewcontroller 中向上移动模态 UIView(StoryBoard)