iOS-防止按钮重复点击

释放双眼,带上耳机,听听看~!

前言
我们在开发的过程中,比如点击一个按钮进行网络请求,或者发送验证码,如果用户连续点击可能导致事件连续调用,验证码会多次发送,在实际开发中我们可以使用enabled来控制,但是在项目中如果对大量的UIButton做控制,这样显然比较麻烦;我们可以考虑通过runtime个UIButton添加一个属性来控制;自定义一个中转方法来接收系统方法,然后我们在自定义的事件接收方法里面来判断是否需要响应,这里也用到runtime的方法交换的方法!

话不多说,上代码!

代码
.h中的代码

//
//  UIButton+ZFJEventInterval.h
//  MY_DEMO
//
//  Created by 张福杰 on 2016/01/13.
//  Copyright © 2019 张福杰. All rights reserved.
//
 
#import <UIKit/UIKit.h>
 
@interface UIButton (ZFJEventInterval)
 
/**
 设置按钮的点击响应间隔时间
 */
@property (nonatomic, assign) NSTimeInterval zfj_eventInterval;
 
@end

.m中的代码

//
//  UIButton+ZFJEventInterval.m
//  MY_DEMO
//
//  Created by 张福杰 on 2016/01/13.
//  Copyright © 2019 张福杰. All rights reserved.
//
 
#import "UIButton+ZFJEventInterval.h"
#import <objc/runtime.h>
 
static char * const zfj_eventIntervalKey = "zfj_eventIntervalKey";
static char * const eventUnavailableKey = "eventUnavailableKey";
 
@interface UIButton ()
 
@property (nonatomic, assign) BOOL eventUnavailable;
 
@end
 
@implementation UIButton (QiEventInterval)
 
+ (void)load{
    Method method = class_getInstanceMethod(self, @selector(sendAction:to:forEvent:));
    Method zfj_method = class_getInstanceMethod(self, @selector(zfj_sendAction:to:forEvent:));
    method_exchangeImplementations(method,zfj_method);
}
 
- (void)zfj_sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event {
    if (self.eventUnavailable == NO) {
        self.eventUnavailable = YES;
        [self zfj_sendAction:action to:target forEvent:event];
        [self performSelector:@selector(setEventUnavailable:) withObject:@(NO) afterDelay:self.zfj_eventInterval];
    }
}
 
- (NSTimeInterval)zfj_eventInterval {
    return [objc_getAssociatedObject(self, zfj_eventIntervalKey) doubleValue];
}
 
- (void)setZfj_eventInterval:(NSTimeInterval)zfj_eventInterval{
    objc_setAssociatedObject(self, zfj_eventIntervalKey, @(zfj_eventInterval), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
 
- (BOOL)eventUnavailable {
    return [objc_getAssociatedObject(self, eventUnavailableKey) boolValue];
}
 
- (void)setEventUnavailable:(BOOL)eventUnavailable {
    objc_setAssociatedObject(self, eventUnavailableKey, @(eventUnavailable), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
 
@end

使用

导入头文件

#import "UIButton+MicEventInterval.h"

设置按钮的点击时间间隔

UIButton *button = [[UIButton alloc] init];
    [button addTarget:self action:@selector(intervalButtonClick) forControlEvents:UIControlEventTouchUpInside];
    button.frame = CGRectMake(100, 200, 100, 40);
    //这是时间间隔 2 秒
    button.mic_eventInterval = 2;
    button.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [button setTitle:@"点  击" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [self.view addSubview:button];

 

人已赞赏
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
有新消息 消息中心
搜索