UIApplication扩展获取顶层控制器

class func topViewController(base: UIViewController? = (UIApplication.shared.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
    }

使用:

UIApplication.topViewController()?.navigationController?.setNavigationBarHidden(false, animated: true)

你可能感兴趣的:(UIApplication扩展获取顶层控制器)