0

So, I've updated to Xcode 10 and iOS 12 today and now I'm getting the following error message when I call topViewController from UINavigationController:

Ambiguous use of 'topViewController'

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

Even though the following code works just fine.

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

Does anyone know any changes in iOS 12 regarding this?

edmoks
  • 27
  • 7
  • the topViewController is not change in iOS12. I tested in Xcode10, iOS12 and it has nothing wrong. What is your `navigationController`? – Quoc Nguyen Sep 19 '18 at 03:59
  • UINavigationController – edmoks Sep 19 '18 at 08:44
  • do you have another variable with the name `topViewController`? – ahbou Sep 19 '18 at 10:58
  • Actually there is a class that extends `UINavigationController` and an extension of `UIViewController` that has a variable called `topViewController`. It's legacy code so I'm not sure why it was created like this. But what changed in Xcode 10/iOS 12 that made this code doesn't work anymore? – edmoks Sep 19 '18 at 13:14

1 Answers1

2

I can suggest you this func for getting topViewContoller as an extension. Easy to use as you guess.

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

Usage:

UIApplication.topViewController()
Oliver
  • 599
  • 6
  • 14