Get to UIViewController from UIView?

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

    Combining several already given answers, I'm shipping on it as well with my implementation:

    @implementation UIView (AppNameAdditions)
    
    - (UIViewController *)appName_viewController {
        /// Finds the view's view controller.
    
        // Take the view controller class object here and avoid sending the same message iteratively unnecessarily.
        Class vcc = [UIViewController class];
    
        // Traverse responder chain. Return first found view controller, which will be the view's view controller.
        UIResponder *responder = self;
        while ((responder = [responder nextResponder]))
            if ([responder isKindOfClass: vcc])
                return (UIViewController *)responder;
    
        // If the view controller isn't found, return nil.
        return nil;
    }
    
    @end
    

    The category is part of my ARC-enabled static library that I ship on every application I create. It's been tested several times and I didn't find any problems or leaks.

    P.S.: You don't need to use a category like I did if the concerned view is a subclass of yours. In the latter case, just put the method in your subclass and you're good to go.

提交回复
热议问题