#import <UIKit/UIKit.h>
typedef void(^actionBlock)(void);
@interface UIView (UIViewController)
/**
得到View所在的控制器
@return 控制器
*/
- (UIViewController *)viewController;
/**
给View添加点击事件
@param block 事件传递
*/
- (void)tapActionGesture:(actionBlock)block;
@end
#import "UIView+UIViewController.h"
NSMutableDictionary *blockActionDict;
@interface UIView ()
@end
@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;
}
- (void)tapActionGesture:(actionBlock)block{
[self addBlock:block];
[self whenTouchOne];
}
-(void)addBlock:(actionBlock)block{
if (blockActionDict == nil){
blockActionDict = [[NSMutableDictionary alloc]init];
}
NSLog(@"%lu",(unsigned long)self.hash);
blockActionDict[[NSString stringWithFormat:@"%lu",(unsigned long)self.hash]] = block;
}
-(void)whenTouchOne{
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]init];
tapGesture.numberOfTouchesRequired = 1;
tapGesture.numberOfTapsRequired = 1;
[tapGesture addTarget:self action:@selector(tapAction)];
[self addGestureRecognizer:tapGesture];
}
-(void)tapAction{
NSLog(@"%lu",(unsigned long)self.hash);
actionBlock block = blockActionDict[[NSString stringWithFormat:@"%lu",(unsigned long)self.hash]];
block();
}
@end