[iOS]Objective-C Runtime学习笔记之:为UIButton添加响应block

1.新建UIButton分类

//UIButton+Block.h
#import 

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 
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

你可能感兴趣的:([iOS]Objective-C Runtime学习笔记之:为UIButton添加响应block)