1. 程式人生 > >Runtime實現防止按鈕重複點選

Runtime實現防止按鈕重複點選

最近測試總說由於手速太快,點選按鈕,連續push了兩次頁面。為了防止按鈕短時間內的重複點選,就用runtime實現防止按鈕的重複點選。

標頭檔案

#import <UIKit/UIKit.h>

#define defaultInterval 0.1  //預設時間間隔

@interface UIButton (YQFixMultiClick)
@property (nonatomic, assign) NSTimeInterval timeInterval; // 用這個給重複點選加間隔
@property (nonatomic, assign) BOOL isIgnoreEvent; //YES 不允許點選   NO 允許點選
@end

.m檔案

#import "UIButton+YQFixMultiClick.h"

@implementation UIButton (YQFixMultiClick)
- (NSTimeInterval)timeInterval {
    return [objc_getAssociatedObject(self, _cmd) doubleValue];
}

- (void)setTimeInterval:(NSTimeInterval)timeInterval {
    objc_setAssociatedObject(self, @selector(timeInterval), @(timeInterval), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (BOOL
)isIgnoreEvent { return [objc_getAssociatedObject(self, _cmd) boolValue]; } - (void)setIsIgnoreEvent:(BOOL)isIgnoreEvent { objc_setAssociatedObject(self, @selector(isIgnoreEvent), @(isIgnoreEvent), OBJC_ASSOCIATION_RETAIN_NONATOMIC); } - (void)resetIsIgnoreEvent{ [self setIsIgnoreEvent:NO
]; } + (void)load { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ SEL originSel = @selector(sendAction:to:forEvent:); SEL newSel = @selector(newSendAction:to:forEvent:); Method originMethod = class_getInstanceMethod(self, originSel); Method newMethod = class_getInstanceMethod(self, newSel); BOOL isAdd = class_addMethod(self, originSel, method_getImplementation(newMethod), method_getTypeEncoding(newMethod)); if (isAdd) { class_replaceMethod(self, newSel, method_getImplementation(originMethod), method_getTypeEncoding(originMethod)); }else { method_exchangeImplementations(originMethod, newMethod); } }); } - (void)newSendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event { if ([NSStringFromClass([self class]) isEqualToString:@"UIButton"]) { self.timeInterval = (self.timeInterval == 0) ? defaultInterval : self.timeInterval; if (self.isIgnoreEvent){ return; }else if (self.timeInterval > 0.1){ [self performSelector:@selector(resetIsIgnoreEvent) withObject:nil afterDelay:self.timeInterval]; } } self.isIgnoreEvent = YES; [self newSendAction:action to:target forEvent:event]; } @end

這樣做有個問題就是,所有按鈕都不能快速重複點選了,如果想實現部分按鈕不能重複點選,可以自定義個Button繼承UIButton,讓後給自定義Button增加分類