#import <UIKit/UIKit.h>
@interface UIButton (ClickBlock)
// UIButtonBLock方法
- (void)addTargetUsingBlock:(void (^)(id sender))block;
@end
#import "UIButton+ClickBlock.h"
#import <objc/runtime.h>
@implementation UIButton (ClickBlock)
static const void *ClickBlockKey = "ClickBlock";
- (void)setReturnBlock:(void (^)(id))clickBlock
{
objc_setAssociatedObject(self, ClickBlockKey, clickBlock, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (void (^)(id))returnBlock
{
return objc_getAssociatedObject(self, ClickBlockKey);
}
- (void)ClickAction:(id)sender
{
if (self.returnBlock) {
self.returnBlock(sender);
}
}
- (void)addTargetUsingBlock:(void (^)(id sender))block
{
if (self.returnBlock != block) {
self.returnBlock = block;
}
[self addTarget:self action:@selector(ClickAction:) forControlEvents:UIControlEventTouchUpInside];
}
@end
通过objc_setAssociatedObject
方法添加属性,点击按钮时执行block。
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.button = [[UIButton alloc] initWithFrame:CGRectMake(10, 30, 300, 50)];
[self.button addTargetUsingBlock:^(id sender) {
NSLog(@"click");
}];
[self.button setTitle:@"Demo" forState:UIControlStateNormal];
[self.button setTitleColor:UIColor.labelColor forState:UIControlStateNormal];
[self.view addSubview:self.button];
}