swift 获取控制器

2019-01-15 15:39:33 浏览数 (1)

得到view的控制器

代码语言:javascript复制
/**
    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
    }

得到当前控制器 用途:可以判断当前控制器是哪个控制器 等

代码语言:javascript复制
///获取当前控制器
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!

} 

0 人点赞