ios 限制UIButton點選頻率
在專案中常常會遇到這樣的問題:
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");
}
}