在项目中常常会遇到这样的问题:
button点击就会触发相应的点击事件,比如说是向向服务器发送网络请求或者弹出弹框。
网上一般无非3种方法
1、控制button的enabled属性可用不可用 缺点用户体验效果不好容,易遗忘
2、runtime hook一下 缺点全局button生效,性能代价太大
3、[self performSelector:@selector(timeEnough:) withObject:nil afterDelay:3.0]; 缺点太繁琐代码过多
这里提供第4中解决方案:自定义一个控制频繁点击限制的button
1、继承UIButton
2、定义一个点击代理方法
3、重写-(void)sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event方法
4、与ViewController做属性连线,(不要做action连线)然后设置代理,并且[self.noDoubleBtn addTarget:self action:@selector(null) forControlEvents:UIControlEventTouchUpInside];
代码如下:
#import <UIKit/UIKit.h>
@protocol NoDoubleButtonDelegate <NSObject>
- (void) BtnClick:(UIButton *)btn;
@end
@interface NoDoubleButton : UIButton
@property(weak , nonatomic) id<NoDoubleButtonDelegate> delegate;
@end
#import "NoDoubleButton.h"
BOOL hasLiked = YES;
@implementation NoDoubleButton
-(void)sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event{
if (hasLiked) { // 点击的时候判断hasLiked
hasLiked = NO;// 执行弹框前设置
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
hasLiked = YES; //弹框完成后延时2秒在设置
});
if(self.delegate != NULL){
[self.delegate BtnClick:self];
}
}
}
@end
- (void)viewDidLoad
{
[super viewDidLoad];
self.noDoubleBtn.delegate = self;
self.noDoubleBtnTwo.delegate = self;
[self.noDoubleBtn addTarget:self action:@selector(null) forControlEvents:UIControlEventTouchUpInside];
[self.noDoubleBtnTwo addTarget:self action:@selector(null) forControlEvents:UIControlEventTouchUpInside];
}
- (void) BtnClick:(UIButton *)btn{
if(btn.tag == 0){
NSLog(@"aaaa");
}
if(btn.tag == 1){
NSLog(@"bbbb");
}
}