获得最顶级的 UIViewController

获得最高 UIViewController 的常用方法是获取活动 UIWindow 的 RootViewController。我为此写了一个扩展名:

extension UIApplication {

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