在實際開發(fā)中我們,點擊一個button按鍵時,需要觸發(fā)一個事件去執(zhí)行。用戶在正常操作情況下,單次點擊時,button只會響應(yīng)一次點擊。但是如果用戶多次點擊一個button,那么就會引起這個事件被多次執(zhí)行,導(dǎo)致一些bug的出現(xiàn)。
如何優(yōu)雅解決的這個問題呢?今天我們來使用Runtime來解決UIButton重復(fù)點擊的問題。
首先新建一個分類category,繼承于UIControl,名字自己定義。
UIControl+ZHW.h(.h文件)
@interface UIControl (ZHW)
@property (nonatomic, assign) NSTimeInterval zhw_acceptEventInterval;//添加點擊事件的間隔時間
@property (nonatomic, assign) BOOL zhw_ignoreEvent;//是否忽略點擊事件,不響應(yīng)點擊事件
@end
UIControl+ZHW.m(.m文件)在使用runtime時,需要導(dǎo)入相應(yīng)的庫(objc/runtime.h)
@implementation UIControl (ZHW)
static const char *UIControl_acceptEventInterval = "UIControl_acceptEventInterval";
static const char *UIcontrol_ignoreEvent = "UIcontrol_ignoreEvent";
- (NSTimeInterval)zhw_acceptEventInterval {
return [objc_getAssociatedObject(self, UIControl_acceptEventInterval) doubleValue];
}
- (void)setZhw_acceptEventInterval:(NSTimeInterval)zhw_acceptEventInterval {
objc_setAssociatedObject(self, UIControl_acceptEventInterval, @(zhw_acceptEventInterval), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (BOOL)zhw_ignoreEvent {
return [objc_getAssociatedObject(self, UIcontrol_ignoreEvent) boolValue];
}
- (void)setZhw_ignoreEvent:(BOOL)zhw_ignoreEvent {
objc_setAssociatedObject(self, UIcontrol_ignoreEvent, @(zhw_ignoreEvent), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
+ (void)load {
Method a = class_getInstanceMethod(self, @selector(sendAction:to:forEvent:));
Method b = class_getInstanceMethod(self, @selector(__zhw_sendAction:to:forEvent:));
method_exchangeImplementations(a, b);
}
- (void)__zhw_sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event {
if (self.zhw_ignoreEvent) return;
if (self.zhw_acceptEventInterval > 0) {
self.zhw_ignoreEvent = YES;
[self performSelector:@selector(setZhw_ignoreEvent:) withObject:@(NO) afterDelay:self.zhw_acceptEventInterval];
}
[self __zhw_sendAction:action to:target forEvent:event];
}
@end
在需要用到地方導(dǎo)入UIControl+ZHW.h頭文件設(shè)置button的點擊時間間隔
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIButton *button;
@property (weak, nonatomic) IBOutlet UIView *colorView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.button.zhw_ignoreEvent = NO;
self.button.zhw_acceptEventInterval = 3.0;
}
- (IBAction)runtimeAction:(UIButton *)sender {
NSLog(@"----run click");
[UIView animateWithDuration:3 animations:^{
self.colorView.center = CGPointMake(200, 500);
} completion:^(BOOL finished) {
self.colorView.center = CGPointMake(95, 85);
}];
}
- (IBAction)buttonAction:(UIButton *)sender {
NSLog(@"------comm click");
[UIView animateWithDuration:3 animations:^{
self.colorView.center = CGPointMake(200, 500);
} completion:^(BOOL finished) {
self.colorView.center = CGPointMake(95, 85);
}];
}
運行demo,可以發(fā)現(xiàn)button多次點擊的問題得到了解決。在設(shè)置button的相應(yīng)點擊事件的時間間隔,在這個 間隔時間內(nèi),button只會響應(yīng)一次點擊事件。
附上demo:UIButtonMutablieClick