原文地址: http://blog.csdn.net/uxyheaven/article/details/48009197
今天无意间看到个很不错的小技巧,怕忘记,记录下。
有时候我们不希望用户疯狂的点击某个按钮,比如点击按钮发网络请求的情况,可能因为网络原因,点击一次按钮木有请求到数据,这时候用户可能我疯狂地点击按钮(是我,肯定这么干 - - !),这样很容易出问题。 这时候我们可以设置重复点击按钮的间隔时间:
① 新建个继承自 UIButton 的分类, .h文件增加两个属性
@property(nonatomic,assign)NSTimeInterval repeatClickTime;
@property(nonatomic,assign,readonly)NSTimeInterval lx_acceptedEventTime;
② 因为是分类,想要在外部能够引用就需要runtime 来申明下 .m文件 方法
#import <objc/runtime.h>
static const void *repeatClickTimeKey = &repeatClickTimeKey;
static const void *lx_acceptedEventTimeKey = &lx_acceptedEventTimeKey;
@implementationUIButton (RepeatClick)
- (NSTimeInterval)repeatClickTime
{
return[objc_getAssociatedObject(self,repeatClickTimeKey) doubleValue];
}
- (void)setRepeatClickTime:(NSTimeInterval)repeatClickTime
{
objc_setAssociatedObject(self,repeatClickTimeKey,@(repeatClickTime),OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (NSTimeInterval)lx_acceptedEventTime
{
return[objc_getAssociatedObject(self,lx_acceptedEventTimeKey)doubleValue];
}
- (void)setLx_acceptedEventTime:(NSTimeInterval)lx_acceptedEventTime
{
objc_setAssociatedObject(self,lx_acceptedEventTimeKey,@(lx_acceptedEventTime),OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
③ 过滤按钮点击事件
+(void)load
{
Methoda =class_getInstanceMethod(self,@selector(sendAction:to:forEvent:));
Methodb =class_getInstanceMethod(self,@selector(__lx_sendAction:to:forEvent:));
method_exchangeImplementations(a, b);
}
- (void)__lx_sendAction:(SEL)action to:(id)target forEvent:(UIEvent*)event
{
if(NSDate.date.timeIntervalSince1970-self.lx_acceptedEventTime<self.repeatClickTime) return;
if(self.repeatClickTime>0)
{
self.lx_acceptedEventTime=NSDate.date.timeIntervalSince1970;
}
[self__lx_sendAction:action to:target forEvent:event];
}