#import <UIKit/UIKit.h>
#import <objc/runtime.h>
typedef void(^ButtonSenderBlock) (UIButton* sender);
@interface UIButton (Block)
@property(nonatomic,copy)ButtonSenderBlock block;
+ (instancetype)quickBuildButtonWithFrame:(CGRect)frame title:(NSString *)title color:(UIColor *)color font:(UIFont *)font backgroundImage:(UIImage *)backgroundImage block:(ButtonSenderBlock)block;
@end
#import "UIButton+Block.h"
static const char btnBlock;
@implementation UIButton (Block)
@dynamic block;
-(void)setBlock:(ButtonSenderBlock)block
{
objc_setAssociatedObject(self, &btnBlock, block, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
[self addTarget:self action:@selector(ButtonSenderOpen) forControlEvents:(UIControlEventTouchUpInside)];
}
-(ButtonSenderBlock)block
{
return objc_getAssociatedObject(self, &btnBlock);
}
- (void)ButtonSenderOpen
{
if (self.block)
{
self.block(self);
}
}
+ (instancetype)quickBuildButtonWithFrame:(CGRect)frame title:(NSString *)title color:(UIColor *)color font:(UIFont *)font backgroundImage:(UIImage *)backgroundImage block:(ButtonSenderBlock)block{
UIButton *btn = [[UIButton alloc] initWithFrame:frame];
[btn setTitle:title forState:UIControlStateNormal];
[btn setTitleColor:color forState:UIControlStateNormal];
[btn.titleLabel setFont:font];
[btn setBackgroundImage:backgroundImage forState:UIControlStateNormal];
btn.block = ^(UIButton *sender) {
block(sender);
};
return btn;
}
@end
#import "UIButton+Block.h"
// 调用
UIButton *b = [[UIButton alloc]initWithFrame:CGRectMake(80, 80, 80, 80)];
[b setBackgroundColor:[UIColor redColor]];
b.block = ^(UIButton *sender) {
NSLog(@"gerererer");
};
[self.view addSubview:b];
UIButton *button = [UIButton quickBuildButtonWithFrame:CGRectMake(0, 64, 70, 70) title:@"点击" color:[UIColor redColor] font:[UIFont systemFontOfSize:17] backgroundImage:nil block:^(UIButton *sender) {
NSLog(@"点击事件");
}];
[self.view addSubview:button];