美文网首页
runtime 之给 button 添加 block 事件支持

runtime 之给 button 添加 block 事件支持

作者: ZYiDa | 来源:发表于2019-06-18 16:13 被阅读0次

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


#import <UIKit/UIKit.h>

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 <objc/runtime.h>

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 事件支持

      本文链接:https://www.haomeiwen.com/subject/tlgfqctx.html