美文网首页
button add block

button add block

作者: 风___________ | 来源:发表于2018-12-13 19:34 被阅读12次

目的:为系统的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) {
        
}];

相关文章

网友评论

      本文标题:button add block

      本文链接:https://www.haomeiwen.com/subject/pqabhqtx.html