iOS小技巧–用runtime 控制 UIButton 的重復(fù)點(diǎn)擊間隔

原文地址: http://blog.csdn.net/uxyheaven/article/details/48009197

今天無意間看到個(gè)很不錯(cuò)的小技巧,怕忘記,記錄下。

有時(shí)候我們不希望用戶瘋狂的點(diǎn)擊某個(gè)按鈕,比如點(diǎn)擊按鈕發(fā)網(wǎng)絡(luò)請求的情況,可能因?yàn)榫W(wǎng)絡(luò)原因,點(diǎn)擊一次按鈕木有請求到數(shù)據(jù),這時(shí)候用戶可能我瘋狂地點(diǎn)擊按鈕(是我,肯定這么干 - - ?。@樣很容易出問題。 這時(shí)候我們可以設(shè)置重復(fù)點(diǎn)擊按鈕的間隔時(shí)間:

① 新建個(gè)繼承自 UIButton 的分類, .h文件增加兩個(gè)屬性?

@property(nonatomic,assign)NSTimeInterval repeatClickTime;

@property(nonatomic,assign,readonly)NSTimeInterval lx_acceptedEventTime;


② 因?yàn)槭欠诸?,想要在外部能夠引用就需要runtime 來申明下 ? .m文件 方法

#import <objc/runtime.h>

static const void *repeatClickTimeKey = &repeatClickTimeKey;

static const void *lx_acceptedEventTimeKey = &lx_acceptedEventTimeKey;

@implementationUIButton (RepeatClick)

- (NSTimeInterval)repeatClickTime

{

return[objc_getAssociatedObject(self,repeatClickTimeKey) doubleValue];

}

- (void)setRepeatClickTime:(NSTimeInterval)repeatClickTime

{

objc_setAssociatedObject(self,repeatClickTimeKey,@(repeatClickTime),OBJC_ASSOCIATION_RETAIN_NONATOMIC);

}

- (NSTimeInterval)lx_acceptedEventTime

{

return[objc_getAssociatedObject(self,lx_acceptedEventTimeKey)doubleValue];

}

- (void)setLx_acceptedEventTime:(NSTimeInterval)lx_acceptedEventTime

{

objc_setAssociatedObject(self,lx_acceptedEventTimeKey,@(lx_acceptedEventTime),OBJC_ASSOCIATION_RETAIN_NONATOMIC);

}

③ 過濾按鈕點(diǎn)擊事件

+(void)load

{

Methoda =class_getInstanceMethod(self,@selector(sendAction:to:forEvent:));

Methodb =class_getInstanceMethod(self,@selector(__lx_sendAction:to:forEvent:));

method_exchangeImplementations(a, b);

}

- (void)__lx_sendAction:(SEL)action to:(id)target forEvent:(UIEvent*)event

{

if(NSDate.date.timeIntervalSince1970-self.lx_acceptedEventTime<self.repeatClickTime) return;

if(self.repeatClickTime>0)

{

self.lx_acceptedEventTime=NSDate.date.timeIntervalSince1970;

}

[self__lx_sendAction:action to:target forEvent:event];

}

最后編輯于
?著作權(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ù)。

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

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