swift 獲取控制器

ZY_FlyWay發表於2018-07-16

得到view的控制器


/**
    view 獲取它的控制器
    */
    public func viewController()->UIViewController? {

        var nextResponder: UIResponder? = self

        repeat {
            nextResponder = nextResponder?.next

            if let viewController = nextResponder as? UIViewController {
                return viewController
            }

        } while nextResponder != nil

        return nil
    }

得到當前控制器
用途:可以判斷當前控制器是哪個控制器 等


///獲取當前控制器
func currentVc() ->UIViewController{

    var vc = UIApplication.shared.keyWindow?.rootViewController

    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
    }

    return vc!

} 

相關文章