Get to UIViewController from UIView?

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

    I don't think it's "bad" idea to find out who is the view controller for some cases. What could be a bad idea is to save the reference to this controller as it could change just as superviews change. In my case I have a getter that traverses the responder chain.

    //.h

    @property (nonatomic, readonly) UIViewController * viewController;
    

    //.m

    - (UIViewController *)viewController
    {
        for (UIResponder * nextResponder = self.nextResponder;
             nextResponder;
             nextResponder = nextResponder.nextResponder)
        {
            if ([nextResponder isKindOfClass:[UIViewController class]])
                return (UIViewController *)nextResponder;
        }
    
        // Not found
        NSLog(@"%@ doesn't seem to have a viewController". self);
        return nil;
    }
    

提交回复
热议问题