Swift 获取view所在的ViewController
一:获取view所在的ViewController
由于UIView和UIViewController都继承UIResponder,且其中涉及到UIResponder响应链中的关系,所以先讨论如何找到用户所点击View,当用户点击一个View时,会首先响应UIApplication中的UIWindow然后一步一步往下查找,直到找到用户点击的View。
关系为:UIWindow->ViewController.View->ViewA - - ->用户点击的View,
而获取View所在的ViewController是上面的逆序操作,关系为:view->superView->ViewController->UIWindow->UIApplication->UIDelegete->nil。
//对UIView的扩展
extension UIView{ func getFirstViewController()->UIViewController?{ for view in sequence(first: self.superview, next: {$0?.superview}){ if let responder = view?.next{ if responder.isKind(of: UIViewController.self){ return responder as? UIViewController } } } return nil } }
//实现 override func viewDidLoad() { super.viewDidLoad() //调用 let mView = UIView(frame: CGRect(origin: CGPoint.zero, size:CGSize(width: 100, height: 100))) mView.backgroundColor = UIColor.red self.view.addSubview(mView) //获取mView的ViewController let vc = mView.getFirstViewController() }