block 創(chuàng)建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];
//關(guān)聯(lián)者 索引key 被關(guān)聯(lián)者 類型協(xié)議
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;
調(diào)用
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];