我分别用OC / Swift 写两个常用的防止UIButton重复点击的方法 其实有三种方法 不过那一种太low 不想写
OC 1. 第一种 cancelPreviousPerformRequestsWithTarget
- (void)viewDidLoad {
[super viewDidLoad];
UIButton * btn = [[UIButton alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
btn.backgroundColor = [UIColor redColor];
[btn addTarget:self action:@selector(TB_btnClick) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
}
-(void)TB_btnClick
{
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(PrintHelloWorld) object:nil];
[self performSelector:@selector(PrintHelloWorld) withObject:nil afterDelay:.4];
}
-(void)PrintHelloWorld
{
NSLog(@"点击了有延迟吗");
}
// 间距都会超过0.4s
2017-06-02 18:51:24.351 button_repeat[12220:301281] 点击了有延迟吗
2017-06-02 18:51:24.895 button_repeat[12220:301281] 点击了有延迟吗
2017-06-02 18:51:25.798 button_repeat[12220:301281] 点击了有延迟吗
2017-06-02 18:51:28.222 button_repeat[12220:301281] 点击了有延迟吗
OC 2. 第二种 通过Runtime 写一个UIButton 类别
// 这是类别的源码
#import "UIButton+TBCustom.h"
#import
@interface UIButton()
@property (nonatomic, assign) NSTimeInterval custom_acceptEventInterval; // 可以用这个给重复点击加间隔
@end
@implementation UIButton (TBCustom)
+ (void)load{
Method systemMethod = class_getInstanceMethod(self, @selector(sendAction:to:forEvent:));
SEL sysSEL = @selector(sendAction:to:forEvent:);
Method customMethod = class_getInstanceMethod(self, @selector(custom_sendAction:to:forEvent:));
SEL customSEL = @selector(custom_sendAction:to:forEvent:);
//添加方法 语法:BOOL class_addMethod(Class cls, SEL name, IMP imp, const char *types) 若添加成功则返回No
// cls:被添加方法的类 name:被添加方法方法名 imp:被添加方法的实现函数 types:被添加方法的实现函数的返回值类型和参数类型的字符串
BOOL didAddMethod = class_addMethod(self, sysSEL, method_getImplementation(customMethod), method_getTypeEncoding(customMethod));
//如果系统中该方法已经存在了,则替换系统的方法 语法:IMP class_replaceMethod(Class cls, SEL name, IMP imp,const char *types)
if (didAddMethod) {
class_replaceMethod(self, customSEL, method_getImplementation(systemMethod), method_getTypeEncoding(systemMethod));
}else{
method_exchangeImplementations(systemMethod, customMethod);
}
}
- (NSTimeInterval )custom_acceptEventInterval{
return [objc_getAssociatedObject(self, "UIControl_acceptEventInterval") doubleValue];
}
- (void)setCustom_acceptEventInterval:(NSTimeInterval)custom_acceptEventInterval{
objc_setAssociatedObject(self, "UIControl_acceptEventInterval", @(custom_acceptEventInterval), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (NSTimeInterval )custom_acceptEventTime{
return [objc_getAssociatedObject(self, "UIControl_acceptEventTime") doubleValue];
}
- (void)setCustom_acceptEventTime:(NSTimeInterval)custom_acceptEventTime{
objc_setAssociatedObject(self, "UIControl_acceptEventTime", @(custom_acceptEventTime), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (void)custom_sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event{
// 如果想要设置统一的间隔时间,可以在此处加上以下几句
// 值得提醒一下:如果这里设置了统一的时间间隔,只会影响UIButton, 如果想统一设置,也想影响UISwitch,建议将UIButton分类,改成UIControl分类,实现方法是一样的
if (self.custom_acceptEventInterval <= 0) {
// 如果没有自定义时间间隔,则默认为.4秒
self.custom_acceptEventInterval = .4;
}
// 是否小于设定的时间间隔
BOOL needSendAction = (NSDate.date.timeIntervalSince1970 - self.custom_acceptEventTime >= self.custom_acceptEventInterval);
// 更新上一次点击时间戳
if (self.custom_acceptEventInterval > 0) {
self.custom_acceptEventTime = NSDate.date.timeIntervalSince1970;
}
// 两次点击的时间间隔小于设定的时间间隔时,才执行响应事件
if (needSendAction) {
[self custom_sendAction:action to:target forEvent:event];
}
}
这是测试代码
- (void)viewDidLoad {
[super viewDidLoad];
UIButton * btn = [[UIButton alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
btn.backgroundColor = [UIColor redColor];
[btn addTarget:self action:@selector(TB_btnClick) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
}
-(void)TB_btnClick
{
NSLog(@"点击了有延迟吗");
}
// 测试数据 都不会少于0.4s
2017-06-02 18:56:48.334 button_repeat[12380:305861] 点击了有延迟吗
2017-06-02 18:56:50.110 button_repeat[12380:305861] 点击了有延迟吗
2017-06-02 18:56:50.702 button_repeat[12380:305861] 点击了有延迟吗
2017-06-02 18:56:51.270 button_repeat[12380:305861] 点击了有延迟吗
Swift
swift 第一种
import UIKit
class SWIFTViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.gray
// 第一种方式
StepOne()
}
fileprivate func StepOne(){
let btn = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
btn.backgroundColor = UIColor.green
btn.addTarget(self, action: #selector(btnClick(_:)), for: .touchUpInside)
view.addSubview(btn)
}
func btnClick(_ btn:UIButton){
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(printHelloWorld), object: "abc")
self.perform(#selector(printHelloWorld), with: nil, afterDelay: 0.4)
}
func printHelloWorld(){
print("Swift 打印不出时间- 如果你知道 请大神 告知 --- 是否有延迟")
}
}
// 注释
Swift 打印不出时间- 如果你知道 请大神 告知 --- 是否有延迟
Swift 打印不出时间- 如果你知道 请大神 告知 --- 是否有延迟
Swift 打印不出时间- 如果你知道 请大神 告知 --- 是否有延迟
Swift 第二种. 参考网上的大牛们的
// 首先给UIButton 协议个类的扩展
import UIKit
import Foundation
public extension UIButton{
private struct cs_associatedKeys {
static var accpetEventInterval = "cs_acceptEventInterval"
static var acceptEventTime = "cs_acceptEventTime"
}
/**
重复点击的时间间隔--自己手动随意设置
利用运行时机制 将accpetEventInterval值修改
*/
var cs_accpetEventInterval: TimeInterval {
get {
if let accpetEventInterval = objc_getAssociatedObject(self, &cs_associatedKeys.accpetEventInterval) as? TimeInterval {
return accpetEventInterval }
return 0.4
}
set {
objc_setAssociatedObject(self, &cs_associatedKeys.accpetEventInterval, newValue as TimeInterval, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
/**
重复点击的时间间隔--自己手动随意设置
利用运行时机制 将acceptEventTime值修改
*/
var cs_acceptEventTime : TimeInterval {
get {
if let acceptEventTime = objc_getAssociatedObject(self, &cs_associatedKeys.acceptEventTime) as? TimeInterval {
return acceptEventTime
}
return 0.4
}
set {
objc_setAssociatedObject(self, &cs_associatedKeys.acceptEventTime, newValue as TimeInterval, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
/**
重写初始化方法,在这个方法中实现在运行时方法替换
*/
override open class func initialize() {
let changeBefore: Method = class_getInstanceMethod(self, #selector(UIButton.sendAction(_:to:for:)))
let changeAfter: Method = class_getInstanceMethod(self, #selector(UIButton.cs_sendAction(action:to:for:)))
method_exchangeImplementations(changeBefore, changeAfter)
}
/**
在这个方法中判断接收到当前事件的时间间隔是否满足我们所设定的间隔,会一直循环调用到满足才会return
*/
func cs_sendAction(action: Selector, to target: AnyObject?, for event: UIEvent?) {
if NSDate().timeIntervalSince1970 - self.cs_acceptEventTime < self.cs_accpetEventInterval {
return
}
if self.cs_accpetEventInterval > 0 {
self.cs_acceptEventTime = NSDate().timeIntervalSince1970
}
self.cs_sendAction(action: action, to: target, for: event)
}
}
第二种 测试
import UIKit
class SWIFTViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.gray
// 第二种方式
StepTwo()
}
fileprivate func StepTwo(){
let btn = UIButton(frame: CGRect(x: 100, y: 250, width: 100, height: 100))
btn.backgroundColor = UIColor.red
btn.addTarget(self, action: #selector(btnClickTwo(_:)), for: .touchUpInside)
view.addSubview(btn)
}
func btnClickTwo(_ btn:UIButton){
print("Swift 打印不出时间- 如果你知道 请大神 告知 --- 是否有延迟")
}
}
// 测试
Swift 打印不出时间- 如果你知道 请大神 告知 --- 是否有延迟
Swift 打印不出时间- 如果你知道 请大神 告知 --- 是否有延迟
Swift 打印不出时间- 如果你知道 请大神 告知 --- 是否有延迟
github 地址 https://github.com/tianbinbin/Call_UIButton_Repeat 喜欢点个赞