UIButton防止重复点击
2020-11-27 本文已影响0人
文子飞_
UIButton防止重复点击
方式一:使用userInteractionEnabled或enabled属性+延时
(建议使用userInteractionEnabled,enabled属性normal-icon、selected-icon不能及时切换)
-(void)onCollectionClick:(UIButton*)btn
{
if (btn.userInteractionEnabled) {
btn.selected = !btn.selected;
btn.userInteractionEnabled = NO;
if (self.collectionBack) {
self.collectionBack(btn);
}
}
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
btn.userInteractionEnabled = YES;
});
}
方式二:使用cancelPreviousPerformRequestsWithTarget:selector:object
// 此方法会在连续点击按钮时取消之前的点击事件,从而只执行最后一次点击事件
+ (void)cancelPreviousPerformRequestsWithTarget:(id)aTarget selector:(SEL)aSelector object:(nullable id)anArgument;
// 多长时间后做某件事情
- (void)performSelector:(SEL)aSelector withObject:(nullable id)anArgument afterDelay:(NSTimeInterval)delay;
/** 方法一 */
- (void)ClickBtn:(UIButton *)sender {
NSLog(@"按钮点击了...");
// 此方法会在连续点击按钮时取消之前的点击事件,从而只执行最后一次点击事件
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(buttonClickedAction:) object:sender];
// 多长时间后做某件事情
[self performSelector:@selector(buttonClickedAction:) withObject:btn afterDelay:2.0];
}
- (void)buttonClickedAction:(UIButton *)sender {
NSLog(@"真正开始执行业务 - 比如网络请求...");
}