美文网首页
通过类别给UIButton添加属性

通过类别给UIButton添加属性

作者: 863cda997e42 | 来源:发表于2021-09-22 14:48 被阅读0次
#import <UIKit/UIKit.h>

@interface UIButton (ClickBlock)

// UIButtonBLock方法
- (void)addTargetUsingBlock:(void (^)(id sender))block;
@end
#import "UIButton+ClickBlock.h"
#import <objc/runtime.h>

@implementation UIButton (ClickBlock)

static const void *ClickBlockKey = "ClickBlock";

- (void)setReturnBlock:(void (^)(id))clickBlock
{
    objc_setAssociatedObject(self, ClickBlockKey, clickBlock, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (void (^)(id))returnBlock
{
    return objc_getAssociatedObject(self, ClickBlockKey);
}

- (void)ClickAction:(id)sender
{
    if (self.returnBlock) {
        self.returnBlock(sender);
    }
}

- (void)addTargetUsingBlock:(void (^)(id sender))block
{
    if (self.returnBlock != block) {
        self.returnBlock = block;
    }
    [self addTarget:self action:@selector(ClickAction:) forControlEvents:UIControlEventTouchUpInside];
}

@end

通过objc_setAssociatedObject方法添加属性,点击按钮时执行block。

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.button = [[UIButton alloc] initWithFrame:CGRectMake(10, 30, 300, 50)];

    [self.button addTargetUsingBlock:^(id sender) {
        NSLog(@"click");
    }];
    
    [self.button setTitle:@"Demo" forState:UIControlStateNormal];
    [self.button setTitleColor:UIColor.labelColor forState:UIControlStateNormal];
    [self.view addSubview:self.button];
}

相关文章

网友评论

      本文标题:通过类别给UIButton添加属性

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