防止按鈕被重復(fù)點(diǎn)擊這里提供3種方法:
第一種:先取消之前的操作在執(zhí)行
-?(void)buttonClicked:(id)sender{
//點(diǎn)擊按鈕后先取消之前的操作,再進(jìn)行需要進(jìn)行的操作
[[self class]cancelPreviousPerformRequestsWithTarget:self selector:@selector(buttonClicked:)object:sender];
[self performSelector:@selector(buttonClicked:?)withObject:sender afterDelay:0.2f];
}
第二種:點(diǎn)擊后設(shè)為不可點(diǎn)擊,幾秒后恢復(fù)狀態(tài)
-(void)buttonClicked:(id)sender{
self.button.enabled?= NO;
[self performSelector:@selector(changeButtonStatus)withObject:nil afterDelay:1.0f];//防止重復(fù)點(diǎn)擊
}
-(void)changeButtonStatus{
self.button.enabled?=YES;
}
第三種:runtime?
創(chuàng)建繼承UIButton的Category文件
.h文件
#import
#define?defaultInterval.5//默認(rèn)時(shí)間間隔
@interfaceUIControl?(UIControl_buttonCon)
@property(nonatomic,assign)NSTimeIntervaltimeInterval;//用這個給重復(fù)點(diǎn)擊加間隔
@property(nonatomic,assign)BOOLisIgnoreEvent;//YES不允許點(diǎn)擊NO允許點(diǎn)擊
@end
.m文件
#import"UIControl+UIControl_buttonCon.h"
@implementationUIControl?(UIControl_buttonCon)
-?(NSTimeInterval)timeInterval{
return[objc_getAssociatedObject(self,_cmd)doubleValue];
}
-?(void)setTimeInterval:(NSTimeInterval)timeInterval{
objc_setAssociatedObject(self,@selector(timeInterval),@(timeInterval),OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
//runtime動態(tài)綁定屬性
-?(void)setIsIgnoreEvent:(BOOL)isIgnoreEvent{
objc_setAssociatedObject(self,@selector(isIgnoreEvent),@(isIgnoreEvent),OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
-?(BOOL)isIgnoreEvent{
return[objc_getAssociatedObject(self,_cmd)boolValue];
}
-?(void)resetState{
[selfsetIsIgnoreEvent:NO];
}
+?(void)load{
staticdispatch_once_tonceToken;
dispatch_once(&onceToken,?^{
SELselA?=@selector(sendAction:to:forEvent:);
SELselB?=@selector(mySendAction:to:forEvent:);
MethodmethodA?=class_getInstanceMethod(self,?selA);
MethodmethodB?=class_getInstanceMethod(self,?selB);
//將methodB的實(shí)現(xiàn)添加到系統(tǒng)方法中也就是說將methodA方法指針添加成方法methodB的返回值表示是否添加成功
BOOLisAdd?=class_addMethod(self,?selA,method_getImplementation(methodB),method_getTypeEncoding(methodB));
//添加成功了說明本類中不存在methodB所以此時(shí)必須將方法b的實(shí)現(xiàn)指針換成方法A的,否則b方法將沒有實(shí)現(xiàn)。
if(isAdd)?{
class_replaceMethod(self,?selB,method_getImplementation(methodA),method_getTypeEncoding(methodA));
}else{
//添加失敗了說明本類中有methodB的實(shí)現(xiàn),此時(shí)只需要將methodA和methodB的IMP互換一下即可。
method_exchangeImplementations(methodA,?methodB);
}
});
}
-?(void)mySendAction:(SEL)action?to:(id)target?forEvent:(UIEvent*)event{
if([NSStringFromClass(self.class)isEqualToString:@"UIButton"])?{
self.timeInterval=self.timeInterval==0?defaultInterval:self.timeInterval;
if(self.isIgnoreEvent){
return;
}elseif(self.timeInterval>0){
[selfperformSelector:@selector(resetState)withObject:nilafterDelay:self.timeInterval];
}
}
//此處methodA和methodB方法IMP互換了,實(shí)際上執(zhí)行sendAction;所以不會死循環(huán)
self.isIgnoreEvent=YES;
[selfmySendAction:actionto:targetforEvent:event];
}
@end