我需要找到视图控制器层次结构中最顶层的导航控制器。我无法确定导航控制器和它的顶视图控制器是否可以同时呈现视图控制器,即
NavigationController --Presented - > UIViewController A
|
|
NavigationController.topViewController --Presented - > UIViewController B
这可能同时进行吗?因为我必须遍历到最后的两条路径并比较哪条更长,然后选择正确的路径?
我尝试了什么
我尝试在导航控制器及其顶视图控制器上同时显示视图控制器,但我在LLDB中收到此警告 “尝试在窗口层次结构中显示其视图!”
它没有显示视图控制器(0x100605860),但这总是如此吗?自定义演示文稿是否可以在窗口层次结构中保留视图?
答案 0 :(得分:0)
presentViewController
显示了一个视图控制器。它不会返回视图控制器。如果您未使用UINavigationController
,那么您可能正在寻找presentedViewController
,并且您需要从根开始并向下遍历所呈现的视图。
Swift 3。*
extension UIApplication {
class func topViewController(controller: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
if let navigationController = controller as? UINavigationController {
return topViewController(controller: navigationController.visibleViewController)
}
if let tabController = controller as? UITabBarController {
if let selected = tabController.selectedViewController {
return topViewController(controller: selected)
}
}
if let presented = controller?.presentedViewController {
return topViewController(controller: presented)
}
return controller
}
}
Swift 2
extension UIApplication {
class func topViewController(controller: UIViewController? = UIApplication.sharedApplication().keyWindow?.rootViewController) -> UIViewController? {
if let navigationController = controller as? UINavigationController {
return topViewController(navigationController.visibleViewController)
}
if let tabController = controller as? UITabBarController {
if let selected = tabController.selectedViewController {
return topViewController(selected)
}
}
if let presented = controller?.presentedViewController {
return topViewController(presented)
}
return controller
}
}
您可以在控制器的任何位置使用它
if let topController = UIApplication.topViewController() {
}