防止UIButton重复点击

方法一:僵硬方法

首先, 为UIButton添加一个Category:

@interface UIButton (YK_FixMultiClick)

/**
 添加按钮点击间隔,间隔时间内点击无效
 */
- (void)addClickInterval:(dispatch_time_t)interval;

@end

.m实现

#import "UIButton+YK_FixMultiClick.h"

@implementation UIButton (YK_FixMultiClick)

- (void)addClickInterval:(dispatch_time_t)interval {
    self.userInteractionEnabled = NO;
    NSLog(@"按钮不可点击");
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(interval * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.userInteractionEnabled = YES;
        NSLog(@"按钮恢复点击");
    });
}

@end

使用方法:
在点击方法内调用

- (void)buttonAction:(UIButton *)sender {
    [sender addClickInterval:2];
}

这样, 就给UIButton指定了2s的时间间隔用于防止重复点击.

方法二:优雅方法

使用runtime来对sendAction:to:forEvent:方法进行hook

UIControl的sendAction:to:forEvent:方法用于处理事件响应.
如果我们在该方法的实现中, 添加针对点击事件的时间间隔相关的处理代码, 则能够做到在指定时间间隔中防止重复点击.

首先, 为UIButton添加一个Category:

#import 

NS_ASSUME_NONNULL_BEGIN

@interface UIButton (YK_FixMultiClick)
/** 重复点击的间隔 **/
@property (nonatomic, assign) NSTimeInterval yk_eventInterval;

@end

NS_ASSUME_NONNULL_END

Category不能给类添加属性, 所以以上的cs_acceptEventIntervalcs_acceptEventTime只会有对应的gettersetter方法, 不会添加真正的成员变量.
如果我们不在实现文件中添加其gettersetter方法, 则采用btn.cs_acceptEventInterval = 1; 这种方法尝试访问该属性会出错.

2016-06-29 14:04:52.538 DemoRuntime[17380:1387981] -[UIButton setCs_acceptEventInterval:]: unrecognized selector sent to instance 0x7fe8e154e470

在实现文件中通过runtime的关联对象的方式, 为UIButton添加以上两个属性. 代码如下:

#import "UIButton+YK_FixMultiClick.h"
#import 

@interface UIButton ()
/** 记录点击按钮时的时间 **/
@property (nonatomic, assign) NSTimeInterval yk_eventTime;
@end

@implementation UIButton (YK_FixMultiClick)

// 因category不能添加属性,只能通过关联对象的方式。
static const char *UIControl_eventInterval = "UIControl_eventInterval";
static const char *UIControl_eventTime = "UIControl_eventTime";

- (NSTimeInterval)yk_eventInterval {
    return [objc_getAssociatedObject(self, UIControl_eventInterval) doubleValue];
}
//关联属性对象
- (void)setYk_eventInterval:(NSTimeInterval)yk_eventInterval {
    objc_setAssociatedObject(self, UIControl_eventInterval, @(yk_eventInterval), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (NSTimeInterval)yk_eventTime {
    return [objc_getAssociatedObject(self, UIControl_eventTime) doubleValue];
}
//关联属性对象
- (void)setYk_eventTime:(NSTimeInterval)yk_eventTime {
    objc_setAssociatedObject(self, UIControl_eventTime, @(yk_eventTime), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

// 在load时执行hook
+ (void)load {
    // Method Swizzling
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        SEL selBefore = @selector(sendAction:to:forEvent:);
        SEL selAfter = @selector(yk_sendAction:to:forEvent:);
        //系统原先的响应方法
        Method before = class_getInstanceMethod(self, selBefore);
        //自己编写的响应方法
        Method after = class_getInstanceMethod(self, selAfter);
        
        BOOL isAdd = class_addMethod(self, selBefore, method_getImplementation(after), method_getTypeEncoding(after));
        
        if (isAdd) {
            class_replaceMethod(self, selAfter, method_getImplementation(before), method_getTypeEncoding(before));
        }else{
            //替换系统方法
            //添加失败了 说明本类中有methodB的实现,此时只需要将methodA和methodB的IMP互换一下即可。
            method_exchangeImplementations(before, after);
        }
    });
}

- (void)yk_sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event {
    //当前时间 - 上一次点击按钮的时间 < 设定的时间间隔
    if ([NSDate date].timeIntervalSince1970 - self.yk_eventTime < self.yk_eventInterval) {
        NSLog(@"当前按钮不可点");
        return;
    }
    //点击按钮时记录当前时间
    if (self.yk_eventInterval > 0) {
        self.yk_eventTime = [NSDate date].timeIntervalSince1970;
    }
    //大于设定的时间间隔 响应方法执行
    [self yk_sendAction:action to:target forEvent:event];
}

@end

load方法是在objc库中的一个load_images函数中调用的. 先把二进制映像文件中的头信息取出, 再解析和读出各个模块中的类定义信息, 把实现了load方法的类和Category记录下来, 最后统一执行调用. 主类中的load方法的调用时机要早于Category中的load方法.
关于load和initialize方法, 可参看博客NSObject的load和initialize方法.
因此, 我们在Category中的load方法中, 执行runtime的method swizzling, 即可将UIButton的事件响应方法sendAction:to:forEvent:替换为我们自定义的方法cs_sendAction:to:forEvent:.
关于runtime的关联对象和method swizzling, 这里就不多做介绍了, 可参考博客iOS --- 理解Runtime机制及其使用场景.
那么, 如何使用呢?

btn.yk_eventInterval = 2;

这样, 就给UIButton指定了2s的时间间隔用于防止重复点击.

参考自:icetime17
链接:https://www.jianshu.com/p/7bca987976bd

然而,此链接方法有些许问题,其+ (void)load如下
+ (void)load {
//系统原先的响应方法
Method before = class_getInstanceMethod(self, @selector(sendAction:to:forEvent:));
//自己编写的响应方法
Method after = class_getInstanceMethod(self, @selector(cs_sendAction:to:forEvent:));
//替换系统方法
method_exchangeImplementations(before, after);
}

导致点击tabBar时会报错:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UITabBarButton yk_eventTime]: unrecognized selector sent to instance 0x105059ee0'

于是我将其+ (void)load方法替换成

+ (void)load {
    // Method Swizzling
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        SEL selBefore = @selector(sendAction:to:forEvent:);
        SEL selAfter = @selector(yk_sendAction:to:forEvent:);
        //系统原先的响应方法
        Method before = class_getInstanceMethod(self, selBefore);
        //自己编写的响应方法
        Method after = class_getInstanceMethod(self, selAfter);
        
        BOOL isAdd = class_addMethod(self, selBefore, method_getImplementation(after), method_getTypeEncoding(after));
        
        if (isAdd) {
            class_replaceMethod(self, selAfter, method_getImplementation(before), method_getTypeEncoding(before));
        }else{
            //替换系统方法
            //添加失败了 说明本类中有methodB的实现,此时只需要将methodA和methodB的IMP互换一下即可。
            method_exchangeImplementations(before, after);
        }
    });
}

解决问题

此方法来自:GnodUxn's Blog
链接:https://www.cnblogs.com/wanxudong/p/5984941.html

你可能感兴趣的:(防止UIButton重复点击)