用runtime解決UIButton的重復(fù)點(diǎn)擊

最近遇到一個(gè)需求,項(xiàng)目里的所有按鈕都要添加重復(fù)點(diǎn)擊的判斷

新建一個(gè)分類繼承UIControl(為什么要繼承UIControl,而不是UIButton,因?yàn)?load方法中交換了UIControl的sendAction:to:forEvent:方法,所以在使用UIControl或其子類(比如UISlider)的sendAction:to:forEvent:方法時(shí)會(huì)引起參數(shù)缺失的崩潰。)
直接上代碼吧。

  • UIControl+IgnoreRepetitionEvent.h
#import <UIKit/UIKit.h>
#import <objc/runtime.h>

@interface UIControl (IgnoreRepetitionEvent)
@property (nonatomic, assign) BOOL ignoreEvent; // 是否忽略點(diǎn)擊
@end
  • UIControl+IgnoreRepetitionEvent.m
#import "UIControl+IgnoreRepetitionEvent.h"
#define EVENTINTERVAL 1 // 間隔時(shí)間
@implementation UIControl (IgnoreRepetitionEvent)

+ (void)load{
    // 交換方法
    Method sendEvent = class_getInstanceMethod(self,@selector(sendAction:to:forEvent:));
    Method my_sendEvent = class_getInstanceMethod(self,@selector(my_sendAction:to:forEvent:));
    method_exchangeImplementations(sendEvent, my_sendEvent);
}

- (void)my_sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event{
    if (!self.ignoreEvent) {
        self.ignoreEvent = YES;
        [self my_sendAction:action to:target forEvent:event];
        [self performSelector:@selector(setIgnoreEvent:) withObject:@(NO) afterDelay:EVENTINTERVAL];
    }
}

- (void)setIgnoreEvent:(BOOL)ignoreEvent{
    objc_setAssociatedObject(self, @selector(ignoreEvent), @(ignoreEvent), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (BOOL)ignoreEvent{
    return [objc_getAssociatedObject(self, @selector(ignoreEvent)) boolValue];
}

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

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

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