通过响应者链条找到控制器

Object-C

UIViewController *vc = nil;
        for (UIView* next = [self superview]; next; next = next.superview) {
            UIResponder *nextResponder = [next nextResponder];
            if ([nextResponder isKindOfClass:[UIViewController class]]) {
                vc = (UIViewController *)nextResponder;
                break;
        }
}

swift

- parameter view: 当前view
     
     - returns: view所在的viewcontroller
     */
    class func viewController(_ view:UIView) -> UIViewController  {
        var next = view as? UIView
        
        while next != nil {
            let nextResponder = next?.next
            if let nextResponder =  nextResponder as? UIViewController{
                return nextResponder;
            }
            next = next?.superview
        }
        return UIViewController()
    }

你可能感兴趣的:(通过响应者链条找到控制器)