如何在iOS中防止同一UIButton上发生多个事件?
我想防止连续多次单击同一如何在iOS中防止同一UIButton上发生多个事件?,ios,uibutton,touch,Ios,Uibutton,Touch,我想防止连续多次单击同一ui按钮 我尝试了启用和排他性touch属性,但没有成功。例如: -(IBAction) buttonClick:(id)sender{ button.enabled = false; [UIView animateWithDuration:1.0 delay:0.0 options:UIViewAnimationOptionAllowAnimatedContent animations:^{ // code to execute
ui按钮
我尝试了启用和排他性touch
属性,但没有成功。例如:
-(IBAction) buttonClick:(id)sender{
button.enabled = false;
[UIView animateWithDuration:1.0 delay:0.0 options:UIViewAnimationOptionAllowAnimatedContent animations:^{
// code to execute
}
completion:^(BOOL finished){
// code to execute
}];
button.enabled = true;
}
您所做的是,您只需在块外设置enabled on/off。这是错误的,它执行一次这个方法就会调用,因此它在完成块调用之前不会禁用按钮。相反,您应该在动画完成后重新启用它
-(IBAction) buttonClick:(id)sender{
button.enabled = false;
[UIView animateWithDuration:1.0 delay:0.0 options:UIViewAnimationOptionAllowAnimatedContent animations:^{
// code to execute
}
completion:^(BOOL finished){
// code to execute
button.enabled = true; //This is correct.
}];
//button.enabled = true; //This is wrong.
}
哦,是的,true
和false
,yes
和NO
看起来不错 这是我的解决方案:
NSInteger\u currentClickNum//单击“保存标记”按钮的当前值
//Button click event
- (void)tabBt1nClicked:(UIButton *)sender
{
NSInteger index = sender.tag;
if (index == _currentClickNum) {
NSLog(@"Click on the selected current topic, not execution method, avoiding duplicate clicks");
}else {
[[self class] cancelPreviousPerformRequestsWithTarget:self selector:@selector(tabBtnClicked:) object:sender];
sender.enabled = NO;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
sender.enabled = YES;
});
_currentClickNum = index;
NSLog(@"Column is the current click:%ld",_currentClickNum);
}
}
在我的例子中,设置isEnabled
的速度不够快,无法防止多次点击。我不得不使用一个财产和一个警卫来防止多次窃听。action方法调用一个委托,该委托通常会解除视图控制器,但通过多次点击按钮,它不会解除<如果代码仍在视图控制器上执行,则代码>解除(…)
必须自行取消,不确定。无论如何,我必须在警卫中添加一个手动解除
这是我的解决方案
private var didAlreadyTapDone = false
private var didNotAlreadyTapDone: Bool {return !didAlreadyTapDone}
func done() {
guard didNotAlreadyTapDone else {
self.dismiss(animated: true, completion: nil)
return
}
didAlreadyTapDone = true
self.delegate.didChooseName(name)
}
我没有使用UIView动画,而是决定使用
Timer
类在一段时间间隔后启用按钮。以下是使用Swift 4的答案:
@IBAction func didTouchButton(_ sender: UIButton) {
sender.isUserInteractionEnabled = false
//Execute your code here
Timer.scheduledTimer(withTimeInterval: 2, repeats: false, block: { [weak sender] timer in
sender?.isUserInteractionEnabled = true
})
}
设置启用应该有效-显示您尝试的代码。正如@Paulw11所说,设置启用应该有效,如果您向我们提供代码,我们可以更好地帮助您。请添加一些代码。我正在将其用于动画。我编辑了一个问题,请看一下。你能解释一下你的问题吗。连续多次点击意味着如果你点击一次,它会调用多次。是吗?对我不起作用,而是尝试了这个: