iOS 12 / Xcode 10 中的 topViewController

topViewController in iOS 12 / Xcode 10

所以,我今天更新到 Xcode 10 和 iOS 12,现在当我从 UINavigationController 调用 topViewController 时收到以下错误消息:

Ambiguous use of 'topViewController'

if let myVC = navigationController.topViewController as? MyViewController {}

即使下面的代码工作得很好。

if let myVC = navigationController.visibleViewController as? MyViewController {}

有人知道 iOS 12 中关于此的任何更改吗?

我可以建议您使用此功能来获取 topViewController 作为扩展。简单易用,如你所想。

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

用法:

UIApplication.topViewController()