簡體   English   中英

如何顯示倒數計時器

[英]how to display a countdown timer

我不知道該怎么做。 我有一個按鈕,一旦點擊它,我想在五秒鍾內開始一個過程,而在用戶等待時,我想顯示倒數-5,4,3,2,1

我無法使用nstimer嘗試此操作,但這不起作用。 有什么建議么? 謝謝

您可以使用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)];
    });
}

使用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);

嘗試類似

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

並在倒數達到0時(並且如果視圖卸載)使計時器無效

檢查NSTimer類參考

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM