這里主要用到的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;
//}
}