IOS获取当前页面的控制器

获取当前页面所属的控制器代码:

 //MARK:- 获取当前控制器
static func getCurrentVC() -> UIViewController {
    
    var vc = UIApplication.shared.keyWindow?.rootViewController
    
    while(true) {
        if (vc?.isKind(of: UITabBarController.self))! {
            vc = (vc as! UITabBarController).selectedViewController
        }else if (vc?.isKind(of: UINavigationController.self))!{
            vc = (vc as! UINavigationController).visibleViewController
        }else if ((vc?.presentedViewController) != nil){
            vc =  vc?.presentedViewController
        } else {
            break
        }
    }
    
    return vc!
}

你可能感兴趣的:(IOS获取当前页面的控制器)