话不多说,上代码
1.新建一个分类UIControl+FixMultiClick
.h
@interfaceUIControl (FixMultiClick)
//防止多次点击间隔时间
@property(nonatomic,assign)NSTimeInterval acceptEventInterval;
//记录每次的点击时间
@property (nonatomic, assign) NSTimeInterval acceptEventTime;
@end
.m
@implementationUIControl (FixMultiClick)
+ (void)load{
MethodoriginalMethod =class_getInstanceMethod(self,@selector(sendAction:to:forEvent:));
MethodnewMethod =class_getInstanceMethod(self,@selector(ms_sendAction:to:forEvent:));
method_exchangeImplementations(originalMethod, newMethod);
}
- (void)setAcceptEventInterval:(NSTimeInterval)acceptEventInterval{
objc_setAssociatedObject(self, @selector(acceptEventInterval), @(acceptEventInterval), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (NSTimeInterval)acceptEventInterval{
NSTimeIntervalinterval =1.5;
if(objc_getAssociatedObject(self,@selector(acceptEventInterval))){
return[objc_getAssociatedObject(self,@selector(acceptEventInterval))doubleValue];
}
returninterval;
}
- (void)setAcceptEventTime:(NSTimeInterval)acceptEventTime{
objc_setAssociatedObject(self, @selector(acceptEventTime), @(acceptEventTime), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (NSTimeInterval)acceptEventTime{
return [objc_getAssociatedObject(self, @selector(acceptEventTime)) doubleValue];
}
- (void)ms_sendAction:(SEL)action to:(id)target forEvent:(UIEvent*)event{
if(![self isKindOfClass:[UIButton class]]){
[selfms_sendAction:actionto:targetforEvent:event];
return;
}
//判定是否在间隔时间内
if (([NSDate date].timeIntervalSince1970 - self.acceptEventTime) < self.acceptEventInterval) {
return;
}
if(self.acceptEventInterval > 0){
self.acceptEventTime = [NSDate date].timeIntervalSince1970;
}
[selfms_sendAction:actionto:targetforEvent:event];
}
@end
2.思路
runtime给category增加属性acceptEventInterval和acceptEventTime 用来判定点击事件间隔。然后再用交换方法swizzing到UIControl的事件传递方法sendAction:(SEL)action to:(id)target forEvent:(UIEvent*)event实现点击操作的自定义。
3.注意事项
截取到点击事件后要区分响应来源区别是否是UIButton UIbarButton 或者其他事件源。
if(![self isKindOfClass:[UIButton class]]){
[selfms_sendAction:actionto:targetforEvent:event];
return;
}
4.仓库地址
https://github.com/yj9294/UIButtonSwizzling
欢迎指导
网友评论