Runtime實現(xiàn)防止按鈕重復(fù)點擊

最近測試總說由于手速太快,點擊按鈕,連續(xù)push了兩次頁面。為了防止按鈕短時間內(nèi)的重復(fù)點擊,就用runtime實現(xiàn)防止按鈕的重復(fù)點擊。

頭文件

#import <UIKit/UIKit.h>

#define defaultInterval 0.1  //默認時間間隔

@interface UIButton (YQFixMultiClick)
@property (nonatomic, assign) NSTimeInterval timeInterval; // 用這個給重復(fù)點擊加間隔
@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

這樣做有個問題就是,所有按鈕都不能快速重復(fù)點擊了,如果想實現(xiàn)部分按鈕不能重復(fù)點擊,可以自定義個Button繼承UIButton,讓后給自定義Button增加分類

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容