如何在AppDelegate中显示当前显示的UIViewController?

我正在尝试获取当前显示的不在AppDelegate中的UIViewController ,但它似乎总是得到最初的顶级UIViewController ,而不是现在的UIViewController

AppDelegate中的以下代码可以获取当前的UIViewController ,但是当我在任何一个View控制器中使用它时,同样的function不起作用:

 func getTopViewController() -> UIViewController { var topViewController = UIApplication.sharedApplication().delegate!.window!!.rootViewController! while (topViewController.presentedViewController != nil) { topViewController = topViewController.presentedViewController! } return topViewController } 

上面的代码是作为类似问题的答案提供的: 在AppDelegate.m中获取当前在屏幕上显示UIViewController的内容

无论我有多深入,我都只能检索出最前面的View Controller。

如何获取当前呈现的UIViewController

仅供参考:我没有使用UINavigationController ,只是常规的UIViewController类。

我不喜欢使用它,但有时它是必要的。

 static func getTopViewController() -> UIViewController { var viewController = UIViewController() if let vc = UIApplication.shared.delegate?.window??.rootViewController { viewController = vc var presented = vc while let top = presented.presentedViewController { presented = top viewController = top } } return viewController } 

**编辑:

这是一个改进版本,它将始终获得最顶级的视图控制器

 static var top: UIViewController? { get { return topViewController() } } static var root: UIViewController? { get { return UIApplication.shared.delegate?.window??.rootViewController } } static func topViewController(from viewController: UIViewController? = UIViewController.root) -> UIViewController? { if let tabBarViewController = viewController as? UITabBarController { return topViewController(from: tabBarViewController.selectedViewController) } else if let navigationController = viewController as? UINavigationController { return topViewController(from: navigationController.visibleViewController) } else if let presentedViewController = viewController?.presentedViewController { return topViewController(from: presentedViewController) } else { return viewController } } 

以下是一个函数中的相同想法:

 func topController(_ parent:UIViewController? = nil) -> UIViewController { if let vc = parent { if let tab = vc as? UITabBarController, let selected = tab.selectedViewController { return topController(selected) } else if let nav = vc as? UINavigationController, let top = nav.topViewController { return topController(top) } else if let presented = vc.presentedViewController { return topController(presented) } else { return vc } } else { return topController(UIApplication.shared.keyWindow!.rootViewController!) } } 

在Swift 4项目中为我工作