在實際開發中我們,點擊一個button按鍵時,需要觸發一個事件去執行。使用者在正常操作情況下,單次點擊時,button只會響應一次點擊。但是如果使用者多次點擊一個button,那麼就會引起這個事件被多次執行,導致一些bug的出現。
如何優雅解決的這個問題呢。今天我們來使用Runtime來解決UIButton重複點擊的問題。
首先建立一個分類category,繼承於UIControl,名字自己定義。
UIControl+ZHW.h(.h檔案)
@interface UIControl (ZHW)@property (nonatomic, assign) NSTimeInterval zhw_acceptEventInterval;//添加點擊事件的間隔時間@property (nonatomic, assign) BOOL zhw_ignoreEvent;//是否忽略點擊事件,不響應點擊事件@end
UIControl+ZHW.m(.m檔案)在使用runtime時,需要匯入相應的庫(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
在需要用到地方匯入UIControl+ZHW.h標頭檔設定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,可以發現button多次點擊的問題得到瞭解決。在設定button的相應點擊事件的時間間隔,在這個 間隔時間內,button只會響應一次點擊事件。
附上demo:UIButtonMutablieClick