UIButton小技巧----点击事件时间间隔

UIButton小技巧—-点击事件时间间隔

起因

      在开发过程中对于UIbutton的点击事件,如果进行频繁的点击,可能会造成事件的不必要的重复执行事件,甚至造成不必要的错误。

解决方案

     通过添加Category,重写sendAction:to:forEvent:方法。(通过runtime交换系统的sendAction:to:forEvent: 和 自定义的customSendAction:to:forEvent:方法,在定义方法中进行时间判断是否符合时间间隔需求,不符合直接return否则在调用系统的sendAction:to:forEvent:)。

代码

#import <UIKit/UIKit.h>

@interface UIButton (TimeInterval)

@property NSTimeInterval repeatEventInterval;

@end
#import "UIButton+TimeInterval.h"
#import <objc/runtime.h>

const char *repeatEventIntervalKey  = "repeatEventIntervalKey";
const char *previousClickTimeKey = "previousClickTimeKey";

@implementation UIButton (TimeInterval)

+ (void)load {
    Method sendAction = class_getInstanceMethod([self class], @selector(sendAction:to:forEvent:));
    Method customSendAction = class_getInstanceMethod([self class], @selector(customSendAction:to:forEvent:));

    method_exchangeImplementations(sendAction, customSendAction);
}

- (void)sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event {
    [super sendAction:action to:target forEvent:event];
}

- (void)setRepeatEventInterval:(NSTimeInterval)repeatEventInterval {
    objc_setAssociatedObject(self, repeatEventIntervalKey, @(repeatEventInterval), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (NSTimeInterval)repeatEventInterval {
    return (NSTimeInterval)[objc_getAssociatedObject(self, repeatEventIntervalKey) doubleValue];
}

- (void)setPreviousClickTime:(NSTimeInterval)previousClickTime {
    objc_setAssociatedObject(self, previousClickTimeKey, @(previousClickTime), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (NSTimeInterval)previousClickTime {
    return [objc_getAssociatedObject(self, previousClickTimeKey) doubleValue];
}

- (void)customSendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event {
    if ( NSDate.date.timeIntervalSince1970 - self.previousClickTime < self.repeatEventInterval ) {
        return;
    }

    if (self.repeatEventInterval > 0) {
        self.previousClickTime = NSDate.date.timeIntervalSince1970 ;
    }

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

@end

应用

#import "UIButton+TimeInterval.h"

button.repeatEventInterval = 2;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值