1. 程式人生 > >iOS 獲取view的controller UIView+UIViewController

iOS 獲取view的controller UIView+UIViewController

直接上程式碼,簡單易懂:

#import "UIView+UIViewController.h"

@implementation UIView (UIViewController)

- (UIViewController *)viewController {
   
    //通過響應者鏈,取得此檢視所在的檢視控制器
    UIResponder *next = self.nextResponder;
    do {
        
        //判斷響應者物件是否是檢視控制器型別
        if ([next isKindOfClass:[UIViewController class]]) {
            return (UIViewController *)next;
        }
        
        next = next.nextResponder;
        
    }while(next != nil);
    
    return nil;
}

@end