Vickate_iOS_设置 UIButton 点击时间间隔,防止连续重复点击
2017-03-17 15:40
411 查看
开发的过程中,总会遇到多多少少的压力测试,比如疯狂的点击 button,导致最后的崩溃。
解决方案:runtime 机制 Method Swizzle 黑魔法,不多 BB,直接上代码
.h文件
.m文件
解决方案:runtime 机制 Method Swizzle 黑魔法,不多 BB,直接上代码
.h文件
#define defaultInterval .5 //默认时间间隔 #import <UIKit/UIKit.h> @interface UIButton (touch) /**设置点击时间间隔*/ @property (nonatomic, assign) NSTimeInterval timeInterval; @end
.m文件
+ (void)load{ static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ SEL selA = @selector(sendAction:to:forEvent:); SEL selB = @selector(mySendAction:to:forEvent:); Method methodA = class_getInstanceMethod(self,selA); Method methodB = class_getInstanceMethod(self, selB); //将 methodB的实现 添加到系统方法中 也就是说 将 methodA方法指针添加成 方法methodB的 返回值表示是否添加成功 BOOL isAdd = 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); } }); } - (NSTimeInterval)timeInterval { return [objc_getAssociatedObject(self, _cmd) doubleValue]; } - (void)setTimeInterval:(NSTimeInterval)timeInterval { objc_setAssociatedObject(self, @selector(timeInterval), @(timeInterval), OBJC_ASSOCIATION_RETAIN_NONATOMIC); } //当我们按钮点击事件 sendAction 时 将会执行 mySendAction - (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; }else if (self.timeInterval > 0){ [self performSelector:@selector(resetState) withObject:nil afterDelay:self.timeInterval]; } } //此处 methodA和methodB方法IMP互换了,实际上执行 sendAction;所以不会死循环 self.isIgnoreEvent = YES; [self mySendAction:action to:target forEvent:event]; } //runtime 动态绑定 属性 - (void)setIsIgnoreEvent:(BOOL)isIgnoreEvent{ // 注意BOOL类型 需要用OBJC_ASSOCIATION_RETAIN_NONATOMIC 不要用错,否则set方法会赋值出错 objc_setAssociatedObject(self, @selector(isIgnoreEvent), @(isIgnoreEvent), OBJC_ASSOCIATION_RETAIN_NONATOMIC); } - (BOOL)isIgnoreEvent{ //_cmd == @select(isIgnore); 和set方法里一致 return [objc_getAssociatedObject(self, _cmd) boolValue]; } - (void)resetState{ [self setIsIgnoreEvent:NO]; }
相关文章推荐
- 利用runtime懒人实现iOS 防止按钮连续点击 连续响应事件,可以自己设置时间间隔,拖进工程中立即生效
- iOS 防止UIButton 连续点击导致请求多次的问题!
- iOS---防止UIButton重复点击的三种实现方式
- iOS按钮防止连续点击 可以自己设置响应间隔
- iOS 防止UIButton按钮重复点击
- ios中解决UIButton连续重复点击按钮的Bug方法
- iOS---防止UIButton重复点击的三种实现方式
- iOS开发 防止UIButton,cell等重复点击
- iOS开发- 利用runtime拦截UIButton的点击事件,防止重复点击
- iOS小技巧–用runtime 解决UIButton 重复点击问题
- iOS小技巧:用runtime 解决UIButton 重复点击问题
- 项目总结之防止连续点击打开两个重复页面的技巧
- 防止连续点击打开两个重复页面的小技巧
- UIButton防止重复点击的方式
- iOS 基于runtime 解决UIButton重复点击 发送多次请求问题
- iOS小技巧--用runtime 解决UIButton 重复点击问题
- iOS防止Button连续点击
- android 按钮防止连续点击防止按钮重复点击
- UIbutton 防止重复点击
- iOS之使用Runtime解决UIButton多次点击(重复点击)