前言
有時(shí)候button會(huì)重復(fù)響應(yīng)點(diǎn)擊事件膨俐,如果重復(fù)響應(yīng)的話用戶體驗(yàn)就很不好怕轿,所以我們可以想辦法避免重復(fù)響應(yīng),我這里主要使用Category來做的
添加Category
給UIbutton添加一個(gè)Category
.h文件
#import <UIKit/UIKit.h>
@interface UIButton (time)
/* 防止button重復(fù)點(diǎn)擊,設(shè)置間隔 */
@property (nonatomic, assign) NSTimeInterval mm_acceptEventInterval;
@end
.m文件
#import "UIButton+time.h"
#import <objc/runtime.h>
@implementation UIButton (time)
static const char *UIButton_acceptEventInterval = "UIButton_acceptEventInterval";
static const char *UIButton_acceptEventTime = "UIButton_acceptEventTime";
- (NSTimeInterval )mm_acceptEventInterval{
return [objc_getAssociatedObject(self, UIButton_acceptEventInterval) doubleValue];
}
- (void)setMm_acceptEventInterval:(NSTimeInterval)mm_acceptEventInterval{
objc_setAssociatedObject(self, UIButton_acceptEventInterval, @(mm_acceptEventInterval), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (NSTimeInterval )mm_acceptEventTime{
return [objc_getAssociatedObject(self, UIButton_acceptEventTime) doubleValue];
}
- (void)setMm_acceptEventTime:(NSTimeInterval)mm_acceptEventTime{
objc_setAssociatedObject(self, UIButton_acceptEventTime, @(mm_acceptEventTime), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
+ (void)load{
//獲取這兩個(gè)方法
Method systemMethod = class_getInstanceMethod(self, @selector(sendAction:to:forEvent:));
SEL sysSEL = @selector(sendAction:to:forEvent:);
Method myMethod = class_getInstanceMethod(self, @selector(mm_sendAction:to:forEvent:));
SEL mySEL = @selector(mm_sendAction:to:forEvent:);
//添加方法進(jìn)去
BOOL didAddMethod = class_addMethod(self, sysSEL, method_getImplementation(myMethod), method_getTypeEncoding(myMethod));
//如果方法已經(jīng)存在
if (didAddMethod) {
class_replaceMethod(self, mySEL, method_getImplementation(systemMethod), method_getTypeEncoding(systemMethod));
}else{
method_exchangeImplementations(systemMethod, myMethod);
}
/*-----以上主要是實(shí)現(xiàn)兩個(gè)方法的互換,load是gcd的只shareinstance,保證執(zhí)行一次-------*/
}
- (void)mm_sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event{
if (NSDate.date.timeIntervalSince1970 - self.mm_acceptEventTime < self.mm_acceptEventInterval) {
return;
}
if (self.mm_acceptEventInterval > 0) {
self.mm_acceptEventTime = NSDate.date.timeIntervalSince1970;
}
[self mm_sendAction:action to:target forEvent:event];
}
@end
使用
使用的時(shí)候直接設(shè)置間隔時(shí)間即可
button.mm_acceptEventInterval = 3.0f;
如果想下Demo請點(diǎn)擊 這里 下載朽缎。
總結(jié)
以上就是我采用的為button設(shè)置點(diǎn)擊時(shí)間間隔的方法,歡迎大家提出寶貴意見。