Get to UIViewController from UIView?

前端 未结 29 2119
一整个雨季
一整个雨季 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:22

    UIView is a subclass of UIResponder. UIResponder lays out the method -nextResponder with an implementation that returns nil. UIView overrides this method, as documented in UIResponder (for some reason instead of in UIView) as follows: if the view has a view controller, it is returned by -nextResponder. If there is no view controller, the method will return the superview.

    Add this to your project and you're ready to roll.

    @interface UIView (APIFix)
    - (UIViewController *)viewController;
    @end
    
    @implementation UIView (APIFix)
    
    - (UIViewController *)viewController {
        if ([self.nextResponder isKindOfClass:UIViewController.class])
            return (UIViewController *)self.nextResponder;
        else
            return nil;
    }
    @end
    

    Now UIView has a working method for returning the view controller.

提交回复
热议问题