此文章已于 2020.06.19 更新,基于 Swift 5.2
在项目中,我们经常需要获取当前所看到的View Controller,比如从其他App跳回我们的App中时,我们可能需要当前View Controller做些事情。那么怎么获取到当前的View Controller呢?其实非常简单:
/// 返回当前的View Controller
///
/// - Parameter base: 迭代起点
/// - Returns: 当前的View Controller
class func getCurrentViewController(base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
if let nav = base as? UINavigationController {
return getCurrentViewController(base: nav.visibleViewController)
}
if let tab = base as? UITabBarController {
return getCurrentViewController(base: tab.selectedViewController)
}
if let presented = base?.presentedViewController {
return getCurrentViewController(base: presented)
}
return base
}
给UIViewController加一类方法,静态地获取当前View Controller。这基本上满足了绝大多数情况了。使用时只需:
let currentViewController = UIViewController.getCurrentViewController()
点击查看参考来源,Enjoy!