最近看到一篇博客很好, 轉(zhuǎn)來做個筆記, 就是關(guān)于標(biāo)題所說的東西
http://www.reibang.com/p/65ce6471cd0f
新建一個基于UIButton的category, 在.h里面把響應(yīng)點擊事件的屬性聲明出去
@property (nonatomic, assign) NSTimeInterval custom_acceptEventInterval;// 可以用這個給重復(fù)點擊加間隔
來到.m, 先引入runtime的頭文件,
#import <objc/runtime.h>
然后
+ (void)load{
Method systemMethod = class_getInstanceMethod(self, @selector(sendAction:to:forEvent:));
SEL sysSEL = @selector(sendAction:to:forEvent:);
Method customMethod = class_getInstanceMethod(self, @selector(custom_sendAction:to:forEvent:));
SEL customSEL = @selector(custom_sendAction:to:forEvent:);
//添加方法 語法:BOOL class_addMethod(Class cls, SEL name, IMP imp, const char *types) 若添加成功則返回No
// cls:被添加方法的類 name:被添加方法方法名 imp:被添加方法的實現(xiàn)函數(shù) types:被添加方法的實現(xiàn)函數(shù)的返回值類型和參數(shù)類型的字符串
BOOL didAddMethod = class_addMethod(self, sysSEL, method_getImplementation(customMethod), method_getTypeEncoding(customMethod));
//如果系統(tǒng)中該方法已經(jīng)存在了耀里,則替換系統(tǒng)的方法 語法:IMP class_replaceMethod(Class cls, SEL name, IMP imp,const char *types)
if (didAddMethod) {
class_replaceMethod(self, customSEL, method_getImplementation(systemMethod), method_getTypeEncoding(systemMethod));
}else{
method_exchangeImplementations(systemMethod, customMethod);
}
}
- (NSTimeInterval )custom_acceptEventInterval{
return [objc_getAssociatedObject(self, "UIControl_acceptEventInterval") doubleValue];
}
- (void)setCustom_acceptEventInterval:(NSTimeInterval)custom_acceptEventInterval{
objc_setAssociatedObject(self, "UIControl_acceptEventInterval", @(custom_acceptEventInterval), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (NSTimeInterval )custom_acceptEventTime{
return [objc_getAssociatedObject(self, "UIControl_acceptEventTime") doubleValue];
}
- (void)setCustom_acceptEventTime:(NSTimeInterval)custom_acceptEventTime{
objc_setAssociatedObject(self, "UIControl_acceptEventTime", @(custom_acceptEventTime), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (void)custom_sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event{
// 如果想要設(shè)置統(tǒng)一的間隔時間检柬,可以在此處加上以下幾句
// 值得提醒一下:如果這里設(shè)置了統(tǒng)一的時間間隔,會影響UISwitch,如果想統(tǒng)一設(shè)置许起,又不想影響UISwitch,建議將UIControl分類器腋,改成UIButton分類聋袋,實現(xiàn)方法是一樣的
// if (self.custom_acceptEventInterval <= 0) {
// // 如果沒有自定義時間間隔,則默認(rèn)為2秒
// self.custom_acceptEventInterval = 2;
// }
// 是否小于設(shè)定的時間間隔
BOOL needSendAction = (NSDate.date.timeIntervalSince1970 - self.custom_acceptEventTime >= self.custom_acceptEventInterval);
// 更新上一次點擊時間戳
if (self.custom_acceptEventInterval > 0) {
self.custom_acceptEventTime = NSDate.date.timeIntervalSince1970;
}
// 兩次點擊的時間間隔小于設(shè)定的時間間隔時俭尖,才執(zhí)行響應(yīng)事件
if (needSendAction) {
[self custom_sendAction:action to:target forEvent:event];
}
}
用的時候在所在類里引入這個類的頭文件, 注意是#import ""
然后需要的button屬性.custom_acceptEventInterval賦值即可