转载自:https://www.jianshu.com/p/c2243ac4f620
通过Runtime控制UIButton响应事件的时间间隔。思路如下:
1、创建一个UIButton
的类别,使用runtime
为UIButton
增加public
属性qi_eventInterval
和private
属性eventUnavailable
。
2、在+load方法中使用runtime
将UIButton
的-sendAction:to:forEvent:
方法与自定义的-qi_sendAction:to:forEvent:
方法交换Implementation
。
3、使用qi_eventInterval
作为控制eventUnavailable
的计时因子,用eventUnavailable
开控制UIButton
的event
事件是否有效。
@interface UIButton (QiEventInterval)
@property (nonatomic, assign) NSTimeInterval qi_eventInterval;
@end
#import "UIButton+QiEventInterval.h"
#import <objc/runtime.h>
static char * const qi_eventIntervalKey = "qi_eventIntervalKey";
static char * const eventUnavailableKey = "eventUnavailableKey";
@interface UIButton ()
@property (nonatomic, assign) BOOL eventUnavailable;
@end
@implementation UIButton (QiEventInterval)
+ (void)load {
Method method = class_getInstanceMethod(self, @selector(sendAction:to:forEvent:));
Method qi_method = class_getInstanceMethod(self, @selector(qi_sendAction:to:forEvent:));
method_exchangeImplementations(method, qi_method);
}
#pragma mark - Action functions
- (void)qi_sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event {
if (self.eventUnavailable == NO) {
self.eventUnavailable = YES;
[self qi_sendAction:action to:target forEvent:event];
[self performSelector:@selector(setEventUnavailable:) withObject:@(NO) afterDelay:self.qi_eventInterval];
}
}
#pragma mark - Setter & Getter functions
- (NSTimeInterval)qi_eventInterval {
return [objc_getAssociatedObject(self, qi_eventIntervalKey) doubleValue];
}
- (void)setQi_eventInterval:(NSTimeInterval)qi_eventInterval {
objc_setAssociatedObject(self, qi_eventIntervalKey, @(qi_eventInterval), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (BOOL)eventUnavailable {
return [objc_getAssociatedObject(self, eventUnavailableKey) boolValue];
}
- (void)setEventUnavailable:(BOOL)eventUnavailable {
objc_setAssociatedObject(self, eventUnavailableKey, @(eventUnavailable), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end
使用方法:
UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
/* here is some button's configuration codes */
[self.view addSubview:button];
//! 设置按钮的点击响应间隔时间
button.qi_eventInterval = 2.0;