iOS 给button的点击添加时间间隔

前言

有时候button会重复响应点击事件,如果重复响应的话用户体验就很不好,所以我们可以想办法避免重复响应,我这里主要使用Category来做的

添加Category

给UIbutton添加一个Category

.h文件


#import 

@interface UIButton (time)

/* 防止button重复点击,设置间隔 */
@property (nonatomic, assign) NSTimeInterval mm_acceptEventInterval;

@end

.m文件


#import "UIButton+time.h"
#import 

@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{
    //获取这两个方法
    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:);
    
    //添加方法进去
    BOOL didAddMethod = class_addMethod(self, sysSEL, method_getImplementation(myMethod), method_getTypeEncoding(myMethod));
    
    //如果方法已经存在
    if (didAddMethod) {
        class_replaceMethod(self, mySEL, method_getImplementation(systemMethod), method_getTypeEncoding(systemMethod));
    }else{
        method_exchangeImplementations(systemMethod, myMethod);
        
    }
    
    /*-----以上主要是实现两个方法的互换,load是gcd的只shareinstance,保证执行一次-------*/
    
}

- (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

使用

使用的时候直接设置间隔时间即可


button.mm_acceptEventInterval = 3.0f;

如果想下Demo请点击 这里 下载。

总结

以上就是我采用的为button设置点击时间间隔的方法,欢迎大家提出宝贵意见。

你可能感兴趣的:(iOS 给button的点击添加时间间隔)