iOS 解决button重复点击问题
项目中经常遇见,重复提交订单的问题。就像之前,项目中有一个功能是抢红包,我自己点的时候都没有问题,别人点就老各种提示。这种问题有点傻逼,也是必要的技能。
通常我们采用的方法就是
-(void)buttonClick:(UIbutton*)button{
button.enabled=No;
do something(^{
button.enabled=yes;
});
}```
###然而现在有一种新的方法,比这个更智能,更实用
@interface UIControl (FF)
@property (nonatomic, assign) NSTimeInterval fy_acceptEventInterval;
@property (nonatomic, assign) BOOL fy_ignoreEvent;
@end
//实现方法
@implementation UIControl (FF)
static const char *UIControl_acceptEventInterval = "UIControl_acceptEventInterval";
static const char *UIControl_ignoreEvent = "UIControl_ignoreEvent";
-
(NSTimeInterval)fy_acceptEventInterval{
return [objc_getAssociatedObject(self, UIControl_acceptEventInterval) doubleValue];
} -
(void)setFy_acceptEventInterval:(NSTimeInterval)fy_acceptEventInterval{
objc_setAssociatedObject(self, UIControl_acceptEventInterval, @(fy_acceptEventInterval), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
} -
(BOOL)fy_ignoreEvent{
return [objc_getAssociatedObject(self, UIControl_ignoreEvent) boolValue];
} -
(void)setFy_ignoreEvent:(BOOL)fy_ignoreEvent{
objc_setAssociatedObject(self, UIControl_ignoreEvent, @(fy_ignoreEvent), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (void)load{
Method a = class_getInstanceMethod(self, @selector(sendAction:to:forEvent:));
Method b = class_getInstanceMethod(self, @selector(_fy_sendAction:to:forEvent:));
method_exchangeImplementations(a, b);
}
-
(void)_fy_sendAction:(SEL)selector to:(id)target forEvent:(UIEvent*)event{
if (self.fy_ignoreEvent) return;if (self.fy_acceptEventInterval > 0) {
self.fy_ignoreEvent = YES;
[self performSelector:@selector(setFy_ignoreEvent:) withObject:@(NO) afterDelay:self.fy_acceptEventInterval];
}[self _fy_sendAction:selector to:target forEvent:event];
}
@end
创建这样的一个category以后,就可以直接使用按钮的属性(button. fy_acceptEventInterval=2)设置间隔了。
###这样做还是没有完美,我看到@茶色花的评论。如果想修改对应状态的背景图片和对应的title的话,还得继续定制。