0

我不知道该怎么做。我有一个按钮,一旦点击它,我想在五秒钟内启动一个进程,当用户等待时,我想显示倒计时 - 5、4、3、2、1

我无法让这个工作我尝试过使用 nstimer 但这不起作用。有什么建议么?谢谢

4

3 回答 3

2

您可以使用dispatch_after()并利用块捕获范围的方式来跟踪您还剩多少秒。

- (IBAction)buttonHandler:(UIButton *)sender
{
    if (self.countingDown)
        return;

    [self startCountDown];
}

- (void)startCountDown
{
    self.countingDown = YES;
    self.button.enabled = NO;
    int seconds = 5;
    [self countDownFor:seconds];
}


- (void)countDownFor:(int)seconds
{
    self.countDownLabel.text = [NSString stringWithFormat:@"%d",seconds];
    if (seconds == 0) {
        self.countingDown = NO;
        self.button.enabled = YES;
        return; 
    }

    double delayInSeconds = 1.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        [self countDownFor:(seconds - 1)];
    });
}
于 2013-02-06T20:25:21.167 回答
1

GCD 和块的优雅解决方案:

    __block void (^runBlock)(int) = ^(int i) {
        countdownLabel.text = [NSString stringWithFormat:@"%d", i];
        if(i>0) {
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 1*NSEC_PER_SEC);
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                runBlock(i-1);
            });
        } else {
            runBlock = nil; // Breaking retain cycle
            // Time to start your great action!
            // ...
        }
    };

    runBlock(5);
于 2013-02-06T20:45:33.520 回答
0

尝试类似的东西

[NSTimer scheduledTimerWithTimeInterval:1 
                                       target:self
                                     selector:@selector(methodNameUsedToupdateButtonText)
                                     userInfo:nil
                                      repeats:YES];

如果倒计时达到 0(并且如果视图卸载),则使计时器无效

检查NSTimer 类参考

于 2013-02-06T20:16:41.033 回答