runtime 之给 button 添加 block 事件支持

这只是简单的笔记
UIButton+block.h


#import 

NS_ASSUME_NONNULL_BEGIN

typedef void(^buttonBlock)(UIButton *btn);

@interface UIButton (block)

- (void)buttonWithAction:(buttonBlock)buttonBlock forControlEvents:(UIControlEvents)controlEvents;

@end

NS_ASSUME_NONNULL_END

UIButton+block.m

#import "UIButton+block.h"
#import 

static const int targetKey;

@implementation UIButton (block)



- (void)buttonWithAction:(buttonBlock)buttonBlock forControlEvents:(UIControlEvents)controlEvents{
    
    if (buttonBlock) {
        objc_setAssociatedObject(self, &targetKey, buttonBlock, OBJC_ASSOCIATION_COPY);
    }
    
    [self addTarget:self action:@selector(invoke:) forControlEvents:controlEvents];
}

- (void)invoke:(id)sender{
    buttonBlock block = objc_getAssociatedObject(self, &targetKey);
    if (block) {
        block(sender);
    }
}
@end
使用

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 0, 130, 44);
    button.center = self.view.center;
    [button setBackgroundColor:[UIColor groupTableViewBackgroundColor]];
    [button setTitle:@"测试关联对象" forState: UIControlStateNormal];
    [self.view addSubview:button];
    [button buttonWithAction:^(UIButton * _Nonnull btn) {
        NSLog(@"*** %@ ***",btn);
    } forControlEvents:UIControlEventTouchUpInside];

你可能感兴趣的:(runtime 之给 button 添加 block 事件支持)