关闭

用runtime 解决UIButton 重复点击问题

标签: 界面uibutton
79人阅读 评论(0) 收藏 举报
分类:

可以给按钮添加一个属性重复点击间隔, 通过设置这个属性来控制再次接受点击事件的时间间隔。

@interface UIControl (EventInterval)

// 可以用这个给重复点击加间隔
@property (nonatomic, assign) NSTimeInterval hyn_acceptEventInterval;
@property (nonatomic, assign) BOOL hyn_ignoreEvent;//
@end

static const char *UIControl_acceptEventInterval = "UIControl_acceptEventInterval";
static const char *UIcontrol_ignoreEvent = "UIcontrol_ignoreEvent";

- (NSTimeInterval)hyn_acceptEventInterval {
    return [objc_getAssociatedObject(self, UIControl_acceptEventInterval) doubleValue];
}

- (void)setHyn_acceptEventInterval:(NSTimeInterval)hyn_acceptEventInterval {
    objc_setAssociatedObject(self, UIControl_acceptEventInterval, @(hyn_acceptEventInterval), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (BOOL)hyn_ignoreEvent {
    return [objc_getAssociatedObject(self, UIcontrol_ignoreEvent) boolValue];
}

- (void)setHyn_ignoreEvent:(BOOL)hyn_ignoreEvent {
    objc_setAssociatedObject(self, UIcontrol_ignoreEvent, @(hyn_ignoreEvent), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

在app启动的时候,我们hook 所有的按钮的 event

@implementation UIControl (EventInterval)

+ (void)load
{
    Method a = class_getInstanceMethod(self, @selector(sendAction:to:forEvent:));
    Method b = class_getInstanceMethod(self, @selector(__hyn_sendAction:to:forEvent:));

    method_exchangeImplementations(a, b);
}

在我们的点击事件里呢,对点击事件做下过滤

- (void)__hyn_sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event {

    if (self.hyn_ignoreEvent) return;

    if (self.hyn_acceptEventInterval > 0) {

        self.hyn_ignoreEvent = YES;

        [self performSelector:@selector(setHyn_ignoreEvent:) withObject:@(NO) afterDelay:self.hyn_acceptEventInterval];

    }

    [self __hyn_sendAction:action to:target forEvent:event];
}

实际使用起来就是这样

UIButton *tempBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[tempBtn addTarget:self action:@selector(btn_click:) forControlEvents:UIControlEventTouchUpInside];
tempBtn.hyn_acceptEventInterval = 0.5;
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:9903次
    • 积分:170
    • 等级:
    • 排名:千里之外
    • 原创:5篇
    • 转载:16篇
    • 译文:0篇
    • 评论:0条
    文章分类