目的:为系统的button添加block
延展:.h
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
#define WeakObj(o) autoreleasepool{} __weak typeof(o) o##Weak = o;
#define StrongObj(o) autoreleasepool{} __strong typeof(o) o = o##Weak;
typedef void(^ActionBlock)(UIButton *button);
@interface UIButton (Block)
- (void)handleControlEvent:(UIControlEvents)event withBlock:(ActionBlock)block;
@end
NS_ASSUME_NONNULL_END
.m
#import "UIButton+Block.h"
#import <objc/runtime.h>
static char UIButtonBlockKey;
@implementation UIButton (Block)
- (void)handleControlEvent:(UIControlEvents)event withBlock:(ActionBlock)block {
objc_setAssociatedObject(self, &UIButtonBlockKey, block, OBJC_ASSOCIATION_COPY_NONATOMIC);
[self addTarget:self action:@selector(callActionBlock:) forControlEvents:event];
}
- (void)callActionBlock:(UIButton *)sender {
ActionBlock block = (ActionBlock)objc_getAssociatedObject(self, &UIButtonBlockKey);
if (block) {
block(sender);
}
}
@end
使用
@WeakObj(self)
[btn handleControlEvent:UIControlEventTouchUpInside withBlock:^(UIButton * _Nonnull button) {
}];
网友评论