用runtime解决UIButton的重复点击

2019-01-04  本文已影响0人  简直不得输

最近遇到一个需求,项目里的所有按钮都要添加重复点击的判断

新建一个分类继承UIControl(为什么要继承UIControl,而不是UIButton,因为+load方法中交换了UIControl的sendAction:to:forEvent:方法,所以在使用UIControl或其子类(比如UISlider)的sendAction:to:forEvent:方法时会引起参数缺失的崩溃。)
直接上代码吧。

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

@interface UIControl (IgnoreRepetitionEvent)
@property (nonatomic, assign) BOOL ignoreEvent; // 是否忽略点击
@end
#import "UIControl+IgnoreRepetitionEvent.h"
#define EVENTINTERVAL 1 // 间隔时间
@implementation UIControl (IgnoreRepetitionEvent)

+ (void)load{
    // 交换方法
    Method sendEvent = class_getInstanceMethod(self,@selector(sendAction:to:forEvent:));
    Method my_sendEvent = class_getInstanceMethod(self,@selector(my_sendAction:to:forEvent:));
    method_exchangeImplementations(sendEvent, my_sendEvent);
}

- (void)my_sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event{
    if (!self.ignoreEvent) {
        self.ignoreEvent = YES;
        [self my_sendAction:action to:target forEvent:event];
        [self performSelector:@selector(setIgnoreEvent:) withObject:@(NO) afterDelay:EVENTINTERVAL];
    }
}

- (void)setIgnoreEvent:(BOOL)ignoreEvent{
    objc_setAssociatedObject(self, @selector(ignoreEvent), @(ignoreEvent), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (BOOL)ignoreEvent{
    return [objc_getAssociatedObject(self, @selector(ignoreEvent)) boolValue];
}

@end
上一篇下一篇

猜你喜欢

热点阅读