Get the top ViewController in iOS Swift

后端 未结 2 998
不思量自难忘°
不思量自难忘° 2020-12-01 22:36

I want to implement a separate ErrorHandler class, which displays error messages on certain events. The behavior of this class should be called from different other classes.

相关标签:
2条回答
  • 2020-12-01 22:49

    Did you try this from the same link?

    let appDelegate = UIApplication.sharedApplication().delegate as! MYAppDelegate//Your app delegate class name.
    
    
    extension UIApplication {
        class func topViewController(base: UIViewController? = appDelegate.window!.rootViewController) -> UIViewController? {
            if let nav = base as? UINavigationController {
                return topViewController(base: nav.visibleViewController)
            }
            if let tab = base as? UITabBarController {
                if let selected = tab.selectedViewController {
                    return topViewController(base: selected)
                }
            }
            if let presented = base?.presentedViewController {
                return topViewController(base: presented)
            }
            return base
        }
    }
    
    0 讨论(0)
  • 2020-12-01 22:50

    Amit89 brought a way to a solution up. You have to call the .windowproperty of the AppDelegate. So I changed the Swift code from the link below to work as intended to find the topmost ViewController. Make sure, that the view is already in the view hierarchy. So this method cannot be called from a .viewDidLoad

    Extension to find the topmost ViewController*

    extension UIApplication {
      class func topViewController(base: UIViewController? = (UIApplication.sharedApplication().delegate as! AppDelegate).window?.rootViewController) -> UIViewController? {
        if let nav = base as? UINavigationController {
          return topViewController(base: nav.visibleViewController)
        }
        if let tab = base as? UITabBarController {
          if let selected = tab.selectedViewController {
            return topViewController(base: selected)
          }
        }
        if let presented = base?.presentedViewController {
          return topViewController(base: presented)
        }
        return base
      }
    }
    

    This code originated from GitHub user Yonat in a comment to an objectiveC equivalent. I only changed the bits of code to get it to work without the .keyWindow property

    0 讨论(0)
提交回复
热议问题