iOS开发-使用block处理UIButton的点击事件

UIButton+Common.h

@interface UIButton (Common)

@property (nonatomic, copy) void (^btn_block)(UIButton *sender);

+ (UIButton *)buttonWithTitle:(NSString *)title font:(UIFont *)font titleColor:(UIColor *)titleColor bgColor:(UIColor *)bgColor cornerRadius:(float)radius block:(void (^)(UIButton *sender))block;

- (void)handleEvent:(UIControlEvents)events block:(void(^)(UIButton *sender))block;

@end

UIButton+Common.m

#import "UIButton+Common.h"
#import <objc/runtime.h>


@implementation UIButton (Common)
// 静态变量地址唯一不变性
static void *UIBUTTON_KEY = &UIBUTTON_KEY;

+ (UIButton *)buttonWithTitle:(NSString *)title font:(UIFont *)font titleColor:(UIColor *)titleColor bgColor:(UIColor *)bgColor cornerRadius:(float)radius block:(void (^)(UIButton *))block {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitle:title forState:UIControlStateNormal];
    [button.titleLabel setFont:font];
    [button setTitleColor:titleColor forState:UIControlStateNormal];
    [button setBackgroundColor:bgColor];
    [button.layer setCornerRadius:radius];
    button.layer.masksToBounds = YES;
    [button handleEvent:UIControlEventTouchUpInside block:block];
    return button;
}


- (void)setBtn_block:(void (^)(UIButton *))btn_block {
    objc_setAssociatedObject(self, &UIBUTTON_KEY, btn_block, OBJC_ASSOCIATION_COPY);
    // 或者
    // [self bk_associateCopyOfValue:btn_block withKey:&UIBUTTON_KEY];
}

- (void (^)(UIButton *))btn_block {
    return objc_getAssociatedObject(self, &UIBUTTON_KEY);
    // 或者
    // return [self bk_associatedValueForKey:&UIBUTTON_KEY];
}

- (void)handleEvent:(UIControlEvents)events block:(void (^)(UIButton *))block {
    self.btn_block = block;
    [self addTarget:self action:@selector(invoke:) forControlEvents:events];
}

- (void)invoke:(UIButton *)sender {
    if (self.btn_block) {
        self.btn_block(sender);
    }
}

@end
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。