如何防止 iOS 中同一个 UIButton 发生多个事件?

How to prevent multiple event on same UIButton in iOS?

我想防止连续多次点击同一个 UIButton

我尝试使用 enabledexclusiveTouch 属性,但没有用。如:

-(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;
}

您所做的是,您只需在块外设置启用 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.
}

哦,是的,而不是 truefalseYESNO 看起来不错。 :)

这是我的解决方案:

NSInteger _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 不够快,无法防止多次点击。我不得不使用 属性 和一个守卫来防止多次点击。并且操作方法正在调用一个委托,该委托通常会关闭视图控制器,但如果点击多个按钮,它不会关闭。 dismiss(...) 如果代码仍在视图控制器上执行,则必须自行取消,不确定。无论如何,我不得不在守卫中添加一个手册dismiss

这是我的解决方案...

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)
}

我决定使用 Timer class 在一段时间间隔后启用按钮,而不是使用 UIView 动画。这是使用 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
    })
}