ios 如何防止Button被重复多次点击的几种方法
demo地址: https://github.com/HeYunDong/ButtonMCK
button被暴力点击这个问题、我相信很多人都遇到过、现在整理下资料供大家参考!
这里有如下3个方法:
1、使用runtime 机制来解决这个问题;给Button添加一个类别;(Objective-C 利用 Runtime 运行时变成一门动态语言,在开发过程中,使用 Runtime 相关 API 可以实现一些很强大的功能,这里我们简单讲到使用 Runtime 完成为分类增加伪属性、利用 Method SWizzling 来 Hook 方法、实现 NSCoding 自动归档解档、实现 KVO Block、委托等!)
#import
NS_ASSUME_NONNULL_BEGIN
@interfaceUIButton (More)
/**
设置点击的时间间隔
*/
@property(nonatomic,assign)NSTimeIntervaleventTimeInterval;
@end
NS_ASSUME_NONNULL_END
#import "UIButton+More.h"
#import
#define defaultInterval1 //默认时间间隔
@interface UIButton ()
//点击事件
@property (nonatomic, assign) BOOL isIgnoreEvent;
@end
@implementationUIButton (More)
staticconstchar*He_eventTimeInterval ="He_eventTimeInterval";
staticconstchar*He_enventIsIgnoreEvent ="He_enventIsIgnoreEvent";
// runtime 动态绑定 属性
- (void)setIsIgnoreEvent:(BOOL)isIgnoreEvent
{
objc_setAssociatedObject(self, He_enventIsIgnoreEvent, @(isIgnoreEvent), OBJC_ASSOCIATION_ASSIGN);
}
- (BOOL)isIgnoreEvent{
return [objc_getAssociatedObject(self, He_enventIsIgnoreEvent) boolValue];
}
- (NSTimeInterval)eventTimeInterval
{
return [objc_getAssociatedObject(self, He_eventTimeInterval) doubleValue];
}
- (void)setEventTimeInterval:(NSTimeInterval)eventTimeInterval
{
objc_setAssociatedObject(self, He_eventTimeInterval, @(eventTimeInterval), OBJC_ASSOCIATION_ASSIGN);
}
+ (void)load
{
// Method Swizzling
staticdispatch_once_tonceToken;
dispatch_once(&onceToken, ^{
SELselA =@selector(sendAction:to:forEvent:);
SELselB =@selector(he_sendAction:to:forEvent:);
Method methodA = class_getInstanceMethod(self,selA);
Method methodB = class_getInstanceMethod(self, selB);
method_exchangeImplementations(methodA, methodB);
});
}
- (void)he_sendAction:(SEL)action to:(id)target forEvent:(UIEvent*)event
{
if(self.isIgnoreEvent==NO) {
self.isIgnoreEvent = YES;
[selfhe_sendAction:actionto:targetforEvent:event];
// [self performSelector:@selector(setIsIgnoreEvent:) withObject:@(NO) afterDelay:self.eventTimeInterval];
/**或者用下方法*/
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(self.eventTimeInterval * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self setIsIgnoreEvent:NO];
});
}
}
@end
2、给点击方法里设置延迟
-(void)testChlickoneone:(UIButton* )sender{
sender.enabled=NO;
NSLog(@"====点击=one==========1");
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(defaultInterval * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
sender.enabled=YES;
});
}
3、方法
// * 取消延迟执行
// *
// * @param aTarget 一般填self
// * @param aSelector 延迟执行的方法
// * @param anArgument 设置延迟执行时填写的参数(必须和上面performSelector方法中的参数一样)
// cancelPreviousPerformRequestsWithTarget 注意
-(void)testChlicktwo:(UIButton* )sender{
NSLog(@"====点击=two==========2");
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(buttonClickedAction:) object:sender];
[selfperformSelector:@selector(buttonClickedAction:)withObject:senderafterDelay:defaultInterval];
}