以view的点击事件UIGestureRecognizer为例子,使用block的方式进行回调。
首先我们创建一个UIGestureRecognizer的类别。
#import <UIKit/UIKit.h>
typedef void(^MMGestureBlock)(id gestureRecognizer);
@interface UIGestureRecognizer (Block)
+ (instancetype)mm_gestureRecognizerWithActionBlock:(MMGestureBlock)block;
@end
#import "UIGestureRecognizer+Block.h"
#import <objc/runtime.h>
@implementation UIGestureRecognizer (Block)
static const int target_key;
+ (instancetype)mm_gestureRecognizerWithActionBlock:(MMGestureBlock)block {
__typeof(self) weakSelf = self;
return [[weakSelf alloc]initWithActionBlock:block];
}
- (instancetype)initWithActionBlock:(MMGestureBlock)block {
self = [self init];
[self addActionBlock:block];
[self addTarget:self action:@selector(wk_tapClick:)];
return self;
}
- (void)addActionBlock:(MMGestureBlock)block {
if (block) {
objc_setAssociatedObject(self, &target_key, block, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
}
- (void)wk_tapClick:(id)sender {
MMGestureBlock block = objc_getAssociatedObject(self, &target_key);
if (block) {
block(sender);
}
}
@end
我们使用objc_setAssociatedObject来给当前类添加一个关联。然后再使用objc_getAssociatedObject把关联的数据得到。然后进行后续的操作。
引入此类别#import"UIGestureRecognizer+Block.h"
UIView *viewM = [[UIView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
viewM.backgroundColor = [UIColor grayColor];
[self.view addSubview:viewM];
[viewM addGestureRecognizer:[UITapGestureRecognizer mm_gestureRecognizerWithActionBlock:^(id gestureRecognizer) {
NSLog(@"viewM点击事件-------");
}]];
这样我们就可以使用此方法来更简单的使用点击事件了。