如何显示倒数计时器

时间:2013-02-06 20:06:11

标签: ios grand-central-dispatch

我无法弄清楚如何做到这一点。 我有一个按钮,一旦它被点击,我想在五秒内开始一个过程,当用户在等待我想显示倒计时 - 5,4,3,2,1

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

3 个答案:

答案 0 :(得分: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)];
    });
}

答案 1 :(得分: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);

答案 2 :(得分:0)

尝试类似

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

如果倒计时到达0(并且如果视图卸载)

,则使计时器无效

检查NSTimer Class Reference