Get to UIViewController from UIView?

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

    Using the example posted by Brock, I modified it so that it is a category of UIView instead UIViewController and made it recursive so that any subview can (hopefully) find the parent UIViewController.

    @interface UIView (FindUIViewController)
    - (UIViewController *) firstAvailableUIViewController;
    - (id) traverseResponderChainForUIViewController;
    @end
    
    @implementation UIView (FindUIViewController)
    - (UIViewController *) firstAvailableUIViewController {
        // convenience function for casting and to "mask" the recursive function
        return (UIViewController *)[self traverseResponderChainForUIViewController];
    }
    
    - (id) traverseResponderChainForUIViewController {
        id nextResponder = [self nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return nextResponder;
        } else if ([nextResponder isKindOfClass:[UIView class]]) {
            return [nextResponder traverseResponderChainForUIViewController];
        } else {
            return nil;
        }
    }
    @end
    

    To use this code, add it into an new class file (I named mine "UIKitCategories") and remove the class data... copy the @interface into the header, and the @implementation into the .m file. Then in your project, #import "UIKitCategories.h" and use within the UIView code:

    // from a UIView subclass... returns nil if UIViewController not available
    UIViewController * myController = [self firstAvailableUIViewController];
    

提交回复
热议问题