最近遇到一個(gè)需求,項(xiàng)目里的所有按鈕都要添加重復(fù)點(diǎn)擊的判斷
新建一個(gè)分類繼承UIControl(為什么要繼承UIControl,而不是UIButton,因?yàn)?load方法中交換了UIControl的sendAction:to:forEvent:方法,所以在使用UIControl或其子類(比如UISlider)的sendAction:to:forEvent:方法時(shí)會(huì)引起參數(shù)缺失的崩潰。)
直接上代碼吧。
- UIControl+IgnoreRepetitionEvent.h
#import <UIKit/UIKit.h>
#import <objc/runtime.h>
@interface UIControl (IgnoreRepetitionEvent)
@property (nonatomic, assign) BOOL ignoreEvent; // 是否忽略點(diǎn)擊
@end
- UIControl+IgnoreRepetitionEvent.m
#import "UIControl+IgnoreRepetitionEvent.h"
#define EVENTINTERVAL 1 // 間隔時(shí)間
@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