Button添加點(diǎn)擊間隔

這里主要用到的Runtime在Button的分類中添加屬性以及運(yùn)行時(shí)中方法替換.

分類.h文件

#import@interface UIButton (BtnRepetitionClicked)

@property (nonatomic, assign)NSTimeInterval timeInterval;

@end

分類.m文件

#import "UIButton+BtnRepetitionClicked.h"

#import <objc/runtime.h>

static const char completeTimeInterval;

static const char completeEventTime;

@interface UIButton ()

@property (nonatomic ,assign) NSTimeInterval eventTime;

@end

@implementation UIButton (BtnRepetitionClicked)

-(NSTimeInterval)timeInterval { ?//分類中不能直接使用屬性,可以通過(guò)關(guān)聯(lián)set,get方法解決這一問(wèn)題

return [objc_getAssociatedObject(self, &completeTimeInterval) doubleValue];

}

-(void)setTimeInterval:(NSTimeInterval)timeInterval {

//關(guān)聯(lián)的必須是對(duì)象,所以timeInterval需要轉(zhuǎn)成對(duì)象

objc_setAssociatedObject(self, &completeTimeInterval, @(timeInterval), OBJC_ASSOCIATION_COPY_NONATOMIC);

}

-(NSTimeInterval)eventTime {

return [objc_getAssociatedObject(self, &completeEventTime) doubleValue];

}

-(void)setEventTime:(NSTimeInterval)eventTime {

objc_setAssociatedObject(self, &completeEventTime, @(eventTime), OBJC_ASSOCIATION_COPY_NONATOMIC);

}

+(void)load { ?//很有誘惑力的方法

//獲取著兩個(gè)方法

SEL sysSEL = @selector(sendAction:to:forEvent:);//獲取自帶的方法

SEL mySEL = @selector(my_sendAction:to:forEvent:); //獲取自己的方法

//方法的交換也是Runtime的黑盒子,具體實(shí)現(xiàn)網(wǎng)上很多的

[self swizzleMethod:sysSEL withMethod:mySEL]; ? ??

}

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

if (NSDate.date.timeIntervalSince1970 - self.eventTime < self.timeInterval) {

return;

}

if (self.timeInterval > 0) {

self.eventTime = NSDate.date.timeIntervalSince1970;

}

}

[self my_sendAction:action to:target forEvent:event]; //這個(gè)方法小白自己的理解是這樣的:調(diào)用自己的方法,不會(huì)循環(huán)調(diào)用,很神奇.我感覺(jué)應(yīng)該是調(diào)用了自帶的被交換的方法.其實(shí)應(yīng)該是調(diào)用自帶的,要不然我們改的可是自帶的方法,誰(shuí)知道底層是怎么實(shí)現(xiàn)的.(有理解不一樣的,請(qǐng)留言,非常感謝!!!!!)

}

注:這里可以給個(gè)默認(rèn)的間隔(),但是感覺(jué)不好,用戶體驗(yàn)上面有點(diǎn)牽強(qiáng).個(gè)人不提倡

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

if (NSDate.date.timeIntervalSince1970 - self.eventTime < self.timeInterval + 2) {

return;

}

//if (self.timeInterval > 0) {

self.eventTime = NSDate.date.timeIntervalSince1970;

//}

}

最后編輯于
?著作權(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),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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