有几个实际业务场景需要防止UIButton连续重复点击。比如:
1、当通过点击按钮来执行网络请求时,若请求耗时稍长,用户往往会再点一次。这样,就执行了两次请求,造成了资源浪费。
2、在移动终端性能较差时(比如iPhone 6升级到iOS 11😅),连续点击按钮会执行多次事件(比如push出来多个viewController)。
3、防止暴力点击。
方法一:
可通过设置UIButton的enabled属性来防止连续重复点击。此方法不好之处就是单个按钮设置和需要设置该属性的代码比较分散,若需要修改也许涉及的代码部分比较多且分散。

方法二:
通过两个方法来设置延迟响应时间:
+cancelPreviousPerformRequestsWithTarget:selector:object:通过NSObject的该方法可取消前一次点击触发的事件
-performSelector:withObject:afterDelay:该方法控制按钮的响应事件的执行时间间隔。
此方法会在连续点击按钮时取消之前的点击事件,从而只执行最后一次点击事件,不好之处就是会出现延迟现象,若一直在延迟时间内点击按钮,则会一直延迟不响应事件,直到在延迟时间内未点击该按钮才会响应按钮事件。

方法三:(推荐使用,可大量按钮设置)
通过Runtime控制UIButton响应事件的时间间隔。思路如下:
1、创建一个UIButton的类别(Category),使用runtime为UIButton增加public属性-按钮点击间隔时间intervalClickTime和private属性-是否可响应点击事件canClickButton。
2、在+load方法中使用runtime将UIButton的-sendAction:to:forEvent:方法与自定义的-mq_sendAction:to:forEvent:方法交换Implementation。
3、使用间隔时间intervalClickTime作为控制是否可响应点击事件canClickButton的计时因子,用canClickButton来控制UIButton的event事件是否有效。



使用时先导入分类,在设置按钮的时间间隔属性即可。
#import "UIButton+MQIntervalClickButton.h"

网友评论