陈斌彬的技术博客

Stay foolish,stay hungry

UIButton+Block的使用

将UIButton的addTarget: action: forControlEvents:改造成block

建立UIButton+Block,将其引用到.pch中,#import "UIButton+Block.h"

UIButton+Block.h文件

#import <Foundation/Foundation.h>
#import <objc/runtime.h>

typedef void (^ActionBlock)();

@interface UIButton(Block)

@property (readonly) NSMutableDictionary *event;

- (void) handleControlEvent:(UIControlEvents)controlEvent withBlock:(ActionBlock)action;

@end

UIButton+Block.m文件

#import "UIButton+Block.h"

@implementation UIButton(Block)

static char overviewKey;

@dynamic event;

- (void)handleControlEvent:(UIControlEvents)event withBlock:(ActionBlock)block {
    objc_setAssociatedObject(self, &overviewKey, block, OBJC_ASSOCIATION_COPY_NONATOMIC);
    [self addTarget:self action:@selector(callActionBlock:) forControlEvents:event];
}


- (void)callActionBlock:(id)sender {
    ActionBlock block = (ActionBlock)objc_getAssociatedObject(self, &overviewKey);
    if (block) {
        block();
    }
}

@end

截图

UIButton+Block.h文件

img

UIButton+Block.m文件

img

实际使用

UIView *pwdBtnView = [[UIView alloc] initWithFrame:(CGRect) {0, 0, 54, 50}];

UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = (CGRect) {0, 0, 54, 50};
btn.selected = !_mIsCanSeePwd;
[btn handleControlEvent:UIControlEventTouchUpInside withBlock:^
 {
   //添加自己的数据
 }];
[pwdBtnView addSubview:btn];