单击按钮后,将其禁用一段时间(XCode)

时间:2012-09-13 13:46:06

标签: objective-c xcode

我想知道如何在点击后几秒钟禁用按钮。我可以用代码

禁用它
  

button.enabled = button.enabled = NO;

但我不确定如何在几秒钟内完成。

3 个答案:

答案 0 :(得分:6)

使用此代码:

double delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
    button.enabled = NO;
});

编辑:如果您想先禁用按钮并稍后执行某些代码,请执行以下操作:

button.enabled = NO;
double delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
    //this will be executed after 2 seconds
});

答案 1 :(得分:1)

你可以使用

[NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(setButtonEnabled) userInfo:nil repeats:NO];

-(void)setButtonEnabled{
    [myButton setEnabled:YES]
}

将按钮设置为不可见

答案 2 :(得分:0)

感谢@Adam。

对于Swift 3.0:

button.isEnabled = false
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(2000)) {
        btnCheckout.isEnabled = true
}