使用宏
// 防止多次调用
#define kPreventRepeatClickTime(_seconds_) \
static BOOL shouldPrevent; \
if (shouldPrevent) return; \
shouldPrevent = YES; \
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)((_seconds_) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ \
shouldPrevent = NO; \
}); \
Category
UIButton
防止多次点击 ,可以添加分类
//.h
#import <UIKit/UIKit.h>
#import <MBProgressHUD.h>
NS_ASSUME_NONNULL_BEGIN
@interface UIButton (LYTimeInterval)
@property (nonatomic, assign) NSTimeInterval lastTime;
@property (nonatomic, assign) CGFloat lytimeinterval;
///短时间内 重复点击提示语
@property (nonatomic, copy) NSString *tipStr;
@end
NS_ASSUME_NONNULL_END
//.m
#import "UIButton+LYTimeInterval.h"
#import "LYHeader.h"
@implementation UIButton (LYTimeInterval)
/// 交换方法后实现
- (void)ly_sendAction:(SEL)action to:(id)target forEvent:(UIEvent*)event{
if (self.lytimeinterval <= 0) {
[self ly_sendAction:action to:target forEvent:event];
return;
}
NSTimeInterval time = CFAbsoluteTimeGetCurrent();
if ((time - self.lastTime >= self.lytimeinterval)) {
self.lastTime = time;
[self ly_sendAction:action to:target forEvent:event];
}else{
if (self.tipStr) {
[[LYObject object] lyshowNewMessage:self.tipStr];
}
}
}
- (CGFloat)lytimeinterval{
return [objc_getAssociatedObject(self, @selector(lytimeinterval)) doubleValue];
}
- (void)setLytimeinterval:(CGFloat)lytimeinterval{
objc_setAssociatedObject(self, @selector(lytimeinterval), @(lytimeinterval), OBJC_ASSOCIATION_ASSIGN);
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
ly_MethodSwizzling([self class], @selector(sendAction:to:forEvent:), @selector(ly_sendAction:to:forEvent:));
});
}
- (NSTimeInterval)lastTime{
return [objc_getAssociatedObject(self, @selector(lastTime)) doubleValue];
}
- (void)setLastTime:(NSTimeInterval)lastTime{
objc_setAssociatedObject(self, @selector(lastTime), @(lastTime), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (void)setHud:(MBProgressHUD *)hud{
objc_setAssociatedObject(self, @selector(hud), hud, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (MBProgressHUD *)hud{
return objc_getAssociatedObject(self, @selector(hud));
}
- (void)setTipStr:(NSString *)tipStr{
objc_setAssociatedObject(self, @selector(tipStr), tipStr, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (NSString *)tipStr{
return objc_getAssociatedObject(self, @selector(tipStr));
}
@end