iOS - 为UIButton添加链式操作

UIButton+ZJBlock.h

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

NS_ASSUME_NONNULL_BEGIN
typedef void(^ActionBlock)(void);

@interface UIButton (ZJBlock)
- (void)handleEvent:(UIControlEvents)controlEvent withBlock:(ActionBlock)action;
@end

NS_ASSUME_NONNULL_END

UIButton+ZJBlock.m

#import "UIButton+ZJBlock.h"
static char touchKey;
@implementation UIButton (ZJBlock)
- (void)handleEvent:(UIControlEvents)controlEvent withBlock:(ActionBlock)action{
    objc_setAssociatedObject(self,&touchKey,action,OBJC_ASSOCIATION_COPY_NONATOMIC);
    [self addTarget:self action:@selector(callActionBlock:) forControlEvents:controlEvent];
}

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

调用方式

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(100,100,100,44);
    btn.backgroundColor = [UIColor blackColor];
    [self.view addSubview:btn];
    
    [btn handleEvent:UIControlEventTouchUpInside withBlock:^{
        NSLog(@"点击了");
    }];
发布了38 篇原创文章 · 获赞 5 · 访问量 9059

猜你喜欢

转载自blog.csdn.net/zj382561388/article/details/81033773