如何防止iOS中同一个UIButton上的多个事件?

时间:2015-02-05 11:44:24

标签: ios uibutton touch

我希望阻止对同一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;
}

4 个答案:

答案 0 :(得分:13)

您正在做的是,您只需在块外设置启用开/关。这是错误的,它执行一旦这个方法将调用,因此它不会禁用按钮,直到完成块将调用。相反,一旦动画完成,你应该重新启用它。

-(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看起来不错。 :)

答案 1 :(得分:0)

这是我的解决方案:

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

答案 2 :(得分:0)

在我的情况下,设置isEnabled的速度不足以防止多次点击。我不得不使用属性和防护来防止多次攻击。并且action方法正在调用一个委托,它通常会关闭视图控制器但是有多个按钮点击它并没有消失。如果代码仍然在视图控制器上执行,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)
}

答案 3 :(得分:0)

我决定使用Timer类在一段时间后启用按钮,而不是使用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
    })
}