1.新建UIButton分类
//UIButton+Block.h
#import <UIKit/UIKit.h>
typedef void (^btnBlock)();
@interface UIButton (Block)
- (void)addActionWithBlock:(btnBlock)block;
@end
2.实现
- objc_setAssociatedObject
用于给对象添加关联对象,传入 nil
则可以移除已有的关联对象; - objc_getAssociatedObject
用于获取关联对象; - objc_removeAssociatedObjects
用于移除一个对象的所有关联对象。
//UIButton+Block.m
#import "UIButton+Block.h"
#import <objc/runtime.h>
static const char btnKey;
@implementation UIButton (Block)
- (void)addActionWithBlock:(btnBlock)block
{
if (block)
{
objc_setAssociatedObject(self, &btnKey, block, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
[self addTarget:self action:@selector(btnAction) forControlEvents:UIControlEventTouchUpInside];
}
- (void)btnAction
{
btnBlock block = objc_getAssociatedObject(self, &btnKey);
block();
}
@end