在开发的时候,为了减少耦合,将View进行拆分时,有时候会碰到ViewController上加载另一个ViewController的View。这时我们需要获取当前最上层的ViewController,在最上层的ViewController进行push,present等操作。
import Foundation
import UIKit
extension UIApplication {
static func topViewController(base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController)-> UIViewController? {
if let navi = base as? UINavigationController {
return topViewController(base:navi.visibleViewController)
}
if let tab = base as? UITabBarController {
let moreNavigationController = tab.moreNavigationController
if let top = moreNavigationController.topViewController, top.view.window != nil {
return topViewController(base:top)
} else if let selected = tab.selectedViewController {
return topViewController(base:selected)
}
}
if let presented = base?.presentedViewController {
return topViewController(base:presented)
}
return base
}
}