iOS-Swift

Swift - 获取当前的ViewController

2016-11-09  本文已影响3990人  Hesse_Huang

此文章已于 2018.12.05 更新,基于 Swift 4.2

在项目中,我们经常需要获取当前所看到的View Controller,比如从其他App跳回我们的App中时,我们可能需要当前View Controller做些事情。那么怎么获取到当前的View Controller呢?其实非常简单:

extension UIViewController {
    class func current(base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
        if let nav = base as? UINavigationController {
            return current(base: nav.visibleViewController)
        }
        if let tab = base as? UITabBarController {
            return current(base: tab.selectedViewController)
        }
        if let presented = base?.presentedViewController {
            return current(base: presented)
        }
        return base
    }
}

给UIViewController加一类方法,静态地获取当前View Controller。这基本上满足了绝大多数情况了。使用时只需:

let currentViewController = UIViewController.current()

点击查看参考来源,Enjoy!

上一篇下一篇

猜你喜欢

热点阅读