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 


@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

你可能感兴趣的:(iOS开发-使用block处理UIButton的点击事件)