Get to UIViewController from UIView?

前端 未结 29 1761
一整个雨季
一整个雨季 2020-11-22 16:57

Is there a built-in way to get from a UIView to its UIViewController? I know you can get from UIViewController to its UIView

29条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 17:32

    I modified de answer so I can pass any view, button, label etc. to get it's parent UIViewController. Here is my code.

    +(UIViewController *)viewController:(id)view {
        UIResponder *responder = view;
        while (![responder isKindOfClass:[UIViewController class]]) {
            responder = [responder nextResponder];
            if (nil == responder) {
                break;
            }
        }
        return (UIViewController *)responder;
    }
    

    Edit Swift 3 Version

    class func viewController(_ view: UIView) -> UIViewController {
            var responder: UIResponder? = view
            while !(responder is UIViewController) {
                responder = responder?.next
                if nil == responder {
                    break
                }
            }
            return (responder as? UIViewController)!
        }
    

    Edit 2:- Swift Extention

    extension UIView
    {
        //Get Parent View Controller from any view
        func parentViewController() -> UIViewController {
            var responder: UIResponder? = self
            while !(responder is UIViewController) {
                responder = responder?.next
                if nil == responder {
                    break
                }
            }
            return (responder as? UIViewController)!
        }
    }
    

提交回复
热议问题