美文网首页
Runtime实现防止按钮重复点击

Runtime实现防止按钮重复点击

作者: naruto_yuqin | 来源:发表于2018-03-20 10:10 被阅读24次

最近测试总说由于手速太快,点击按钮,连续push了两次页面。为了防止按钮短时间内的重复点击,就用runtime实现防止按钮的重复点击。

头文件

#import <UIKit/UIKit.h>

#define defaultInterval 0.1  //默认时间间隔

@interface UIButton (YQFixMultiClick)
@property (nonatomic, assign) NSTimeInterval timeInterval; // 用这个给重复点击加间隔
@property (nonatomic, assign) BOOL isIgnoreEvent; //YES 不允许点击   NO 允许点击
@end

.m文件

#import "UIButton+YQFixMultiClick.h"

@implementation UIButton (YQFixMultiClick)
- (NSTimeInterval)timeInterval {
    return [objc_getAssociatedObject(self, _cmd) doubleValue];
}

- (void)setTimeInterval:(NSTimeInterval)timeInterval {
    objc_setAssociatedObject(self, @selector(timeInterval), @(timeInterval), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (BOOL)isIgnoreEvent {
    return [objc_getAssociatedObject(self, _cmd) boolValue];
}

- (void)setIsIgnoreEvent:(BOOL)isIgnoreEvent {
    objc_setAssociatedObject(self, @selector(isIgnoreEvent), @(isIgnoreEvent), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (void)resetIsIgnoreEvent{
    [self setIsIgnoreEvent:NO];
}

+ (void)load {
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        SEL originSel = @selector(sendAction:to:forEvent:);
        SEL newSel = @selector(newSendAction:to:forEvent:);
        
        Method originMethod = class_getInstanceMethod(self, originSel);
        Method newMethod = class_getInstanceMethod(self, newSel);
        BOOL isAdd = class_addMethod(self, originSel, method_getImplementation(newMethod), method_getTypeEncoding(newMethod));
        if (isAdd) {
            class_replaceMethod(self, newSel, method_getImplementation(originMethod), method_getTypeEncoding(originMethod));
        }else {
            method_exchangeImplementations(originMethod, newMethod);
        }
    });
}

- (void)newSendAction:(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.1){
            [self performSelector:@selector(resetIsIgnoreEvent) withObject:nil afterDelay:self.timeInterval];
        }
    }
    
    self.isIgnoreEvent = YES;
    [self newSendAction:action to:target forEvent:event];
}
@end

这样做有个问题就是,所有按钮都不能快速重复点击了,如果想实现部分按钮不能重复点击,可以自定义个Button继承UIButton,让后给自定义Button增加分类

相关文章

网友评论

      本文标题:Runtime实现防止按钮重复点击

      本文链接:https://www.haomeiwen.com/subject/tujvqftx.html