防止按钮被重复点击这里提供3种方法:
第一种:先取消之前的操作在执行
- (void)buttonClicked:(id)sender{
//点击按钮后先取消之前的操作,再进行需要进行的操作
[[self class]cancelPreviousPerformRequestsWithTarget:self selector:@selector(buttonClicked:)object:sender];
[self performSelector:@selector(buttonClicked: )withObject:sender afterDelay:0.2f];
}
第二种:点击后设为不可点击,几秒后恢复状态
-(void)buttonClicked:(id)sender{
self.button.enabled = NO;
[self performSelector:@selector(changeButtonStatus)withObject:nil afterDelay:1.0f];//防止重复点击
}
-(void)changeButtonStatus{
self.button.enabled =YES;
}
第三种:runtime
创建继承UIButton的Category文件
.h文件
#import
#define defaultInterval.5//默认时间间隔
@interfaceUIControl (UIControl_buttonCon)
@property(nonatomic,assign)NSTimeIntervaltimeInterval;//用这个给重复点击加间隔
@property(nonatomic,assign)BOOLisIgnoreEvent;//YES不允许点击NO允许点击
@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动态绑定属性
- (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的实现添加到系统方法中也就是说将methodA方法指针添加成方法methodB的返回值表示是否添加成功
BOOLisAdd =class_addMethod(self, selA,method_getImplementation(methodB),method_getTypeEncoding(methodB));
//添加成功了说明本类中不存在methodB所以此时必须将方法b的实现指针换成方法A的,否则b方法将没有实现。
if(isAdd) {
class_replaceMethod(self, selB,method_getImplementation(methodA),method_getTypeEncoding(methodA));
}else{
//添加失败了说明本类中有methodB的实现,此时只需要将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互换了,实际上执行sendAction;所以不会死循环
self.isIgnoreEvent=YES;
[selfmySendAction:actionto:targetforEvent:event];
}
@end