UIButton+Delay.h
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface UIButton (Delay)
/**
按鈕獨(dú)有的防止被多次點(diǎn)擊的屬性
*/
@property (nonatomic, assign) NSTimeInterval eventTimeInterval;
@end
NS_ASSUME_NONNULL_END
UIButton+Delay.m
#import "UIButton+Delay.h"
#import <objc/runtime.h>
#define defaultInterval 5 //默認(rèn)時(shí)間間隔
@interface UIButton ()
/**
bool YES 忽略點(diǎn)擊事件 NO 允許點(diǎn)擊事件
*/
@property (nonatomic, assign) BOOL isIgnoreEvent;
@end
@implementation UIButton (Delay)
static const char *UIControl_eventTimeInterval = "UIControl_eventTimeInterval";
static const char *UIControl_enventIsIgnoreEvent = "UIControl_enventIsIgnoreEvent";
// runtime 動態(tài)綁定 屬性
- (void)setIsIgnoreEvent:(BOOL)isIgnoreEvent {
objc_setAssociatedObject(self, UIControl_enventIsIgnoreEvent, @(isIgnoreEvent), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (BOOL)isIgnoreEvent {
return [objc_getAssociatedObject(self, UIControl_enventIsIgnoreEvent) boolValue];
}
- (NSTimeInterval)eventTimeInterval {
return [objc_getAssociatedObject(self, UIControl_eventTimeInterval) doubleValue];
}
- (void)setEventTimeInterval:(NSTimeInterval)eventTimeInterval {
objc_setAssociatedObject(self, UIControl_eventTimeInterval, @(eventTimeInterval), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
+ (void)load {
// Method Swizzling
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
SEL selA = @selector(sendAction:to:forEvent:);
SEL selB = @selector(_wpf_sendAction:to:forEvent:);
Method methodA = class_getInstanceMethod(self,selA);
Method methodB = class_getInstanceMethod(self, selB);
BOOL isAdd = class_addMethod(self, selA, method_getImplementation(methodB), method_getTypeEncoding(methodB));
if (isAdd) {
class_replaceMethod(self, selB, method_getImplementation(methodA), method_getTypeEncoding(methodA));
}else{
//添加失敗了 說明本類中有methodB的實(shí)現(xiàn),此時(shí)只需要將methodA和methodB的IMP互換一下即可。
method_exchangeImplementations(methodA, methodB);
}
});
}
- (void)_wpf_sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event {
self.eventTimeInterval = self.eventTimeInterval == 0 ? defaultInterval : self.eventTimeInterval;
if (self.isIgnoreEvent){
return;
}else if (self.eventTimeInterval > 0){
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(self.eventTimeInterval * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self setIsIgnoreEvent:NO];
});
}
self.isIgnoreEvent = YES;
// 這里看上去會陷入遞歸調(diào)用死循環(huán),但在運(yùn)行期此方法是和sendAction:to:forEvent:互換的,相當(dāng)于執(zhí)行sendAction:to:forEvent:方法,所以并不會陷入死循環(huán)。
[self _wpf_sendAction:action to:target forEvent:event];
}
@end
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。