主要实现通过runtime动态关联属性。
上码!!!!
#import <UIKit/UIKit.h>
typedef void(^ButtonBlock)(UIButton* btn);
@interface UIButton (Block)
/**
* button 添加点击事件
*
* @param block
*/
- (void)addAction:(ButtonBlock)block;
/**
* button 添加事件
*
* @param block
* @param controlEvents 点击的方式
*/
- (void)addAction:(ButtonBlock)block forControlEvents:(UIControlEvents)controlEvents;
@end
////////////////////////////////////////////////////
#import "UIButton+Block.h"
#import <objc/runtime.h>
@implementation UIButton (Block)
static char ActionTag;
/**
* button 添加点击事件 默认点击方式UIControlEventTouchUpInside
*
* @param block
*/
- (void)addAction:(ButtonBlock)block {
objc_setAssociatedObject(self, &ActionTag, block, OBJC_ASSOCIATION_COPY_NONATOMIC);
[self addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchUpInside];
}
/**
* button 添加事件
*
* @param block
* @param controlEvents 点击的方式
*/
- (void)addAction:(ButtonBlock)block forControlEvents:(UIControlEvents)controlEvents {
objc_setAssociatedObject(self, &ActionTag, block, OBJC_ASSOCIATION_COPY_NONATOMIC);
[self addTarget:self action:@selector(action:) forControlEvents:controlEvents];
}
/**
* button 事件的响应方法
*
* @param sender
*/
- (void)action:(id)sender {
ButtonBlock blockAction = (ButtonBlock)objc_getAssociatedObject(self, &ActionTag);
if (blockAction) {
blockAction(self);
}
}
@end
使用方法如下
UIButton *testButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
testButton.backgroundColor = [UIColor redColor];
[self.view addSubview:testButton];
[testButton addAction:^(UIButton *btn) {
NSLog(@"我被点名了");
}];
[testButton addAction:^(UIButton *btn) {
NSLog(@"我被点名了");
} forControlEvents:UIControlEventTouchUpInside];
O了,喜欢的走心哦...