block 创建imageview
imageview 扩展类
import <objc/runtime.h>
@implementation UIImageView (Action)
static const char KeyMethod;
+(UIImageView *)createImageViewWithFrame:(CGRect)frame imageName:(NSString *)imageName actionBlock:(dispatch_block_t)actionBlock{
UIImageView *imageView = [[UIImageView alloc]initWithFrame:frame];
imageView.userInteractionEnabled = YES;
imageView.image = [UIImage imageNamed:imageName];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:imageView action:@selector(gestureAction:)];
[imageView addGestureRecognizer:tap];
//关联者 索引key 被关联者 类型协议
objc_setAssociatedObject(imageView, &KeyMethod, actionBlock, OBJC_ASSOCIATION_COPY_NONATOMIC);
return imageView;
}
-(void)gestureAction:(UITapGestureRecognizer *)tap{
UIImageView *imageview = (UIImageView *)tap.view;
dispatch_block_t block = (dispatch_block_t)objc_getAssociatedObject(imageview, &KeyMethod);
if (block) {
block();
}
dispatch_block_t block1 = (dispatch_block_t)objc_getAssociatedObject(imageview, &keyOfBlock);
if (block1) {
block1();
}
}
-(dispatch_block_t)actionBlock{
return objc_getAssociatedObject(self, &keyOfBlock);
}
-(void)setActionBlock:(dispatch_block_t)actionBlock{
objc_setAssociatedObject(self, &keyOfBlock, actionBlock, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
@end
合成存取器 样式,重写set get方法
@property(nonatomic,copy)dispatch_block_t actionBlock;
调用
UIImageView *imageview = [UIImageView createImageViewWithFrame:CGRectMake(20, 100, self.view.frame.size.width - 40, 200) imageName:@"1.jpg" actionBlock:^{
float r = random()%255/255.0;
float g = random()%255/255.0;
float b = random()%255/255.0;
self.view.backgroundColor = [UIColor colorWithRed:r green:g blue:b alpha:1];
}];
imageview.actionBlock = ^{
NSLog(@"111");
};
[self.view addSubview:imageview];