ios关联对象给UIView添加tapBlock
#import "UIView+tap.h"
#import <objc/runtime.h>
static char kActionHandlerTapGestureKey;
static char kActionHandlerTapBlockKey;
@implementation UIView (tap)
- (void)setTapWithBlock:(void(^)(void))block {
UITapGestureRecognizer *tap = objc_getAssociatedObject(self, &kActionHandlerTapGestureKey);
if (!tap) {
tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTap:)];
[self addGestureRecognizer:tap];
objc_setAssociatedObject(self, &kActionHandlerTapGestureKey, tap, OBJC_ASSOCIATION_RETAIN);
}
objc_setAssociatedObject(self, &kActionHandlerTapBlockKey, block, OBJC_ASSOCIATION_COPY);
}
- (void)onTap:(UITapGestureRecognizer *)gesture {
if (gesture.state == UIGestureRecognizerStateRecognized) {
void(^action)(void) = objc_getAssociatedObject(self, &kActionHandlerTapBlockKey);
if (action) {
action();
}
}
}
@end
use:
- (void)viewDidLoad {
[super viewDidLoad];
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
view.backgroundColor = [UIColor redColor];
[view setTapWithBlock:^{
NSLog(@"tap");
}];
[self.view addSubview:view];
}