iPhone - 如何找到最顶层的视图控制器 [英] iPhone -- How to find topmost view controller
问题描述
我遇到了几个案例,现在可以方便地找到最顶层的视图控制器(负责当前视图的控制器),但还没有找到办法。
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 found a way to do it.
基本上挑战是这样的:假设一个 在一个不是视图控制器的类中执行 (或视图) [并且没有活动视图的地址] 并且尚未传递最顶层视图控制器的地址(或者说,地址导航控制器),是否有可能找到视图控制器? (如果是这样,怎么样?)
Basically the challenge is this: Given that one is executing in a class that is not a view controller (or a view) [and does not have the address of an active view] and has not been passed the address of the topmost view controller (or, say, the address of the navigation controller), is it possible to find that view controller? (And, if so, how?)
或者,如果失败了,是否可以找到最顶层的视图?
Or, failing that, is it possible to find the topmost view?
推荐答案
我认为您需要结合已接受的答案和@ fishstix的
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 +
let rootViewController = UIApplication.shared.keyWindow?.rootViewController
这篇关于iPhone - 如何找到最顶层的视图控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!