【问题标题】:nstimer count down not working as expectednstimer 倒计时未按预期工作
【发布时间】:2016-11-22 11:46:36
【问题描述】:

我正在使用nstimer 在标签中显示倒数计时器。我可以启动计时器并在标签中显示倒计时,但计时器会跳到下一秒而不是每秒显示一次。如果倒数计时器设置为 10 秒,则倒数计时器标签中仅显示 9、7、5、3、1。

下面是我的代码。

 NSTimer *tktTimer;
 int secondsLeft;


- (void)startTimer {
   secondsLeft = 10;
        tktTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateCountdown) userInfo:nil repeats: YES];
}

-(void) updateCountdown {
    int hours, minutes, seconds;

    secondsLeft--;
    NSLog(@"secondsLeft %d",secondsLeft);//every time it is printing 9,7,5,3,1 but should print 9,8,7,6,5,4,3,2,1,0
    hours = secondsLeft / 3600;
    minutes = (secondsLeft % 3600) / 60;
    seconds = (secondsLeft %3600) % 60;
    countDownlabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];


    if (--secondsLeft == 0) {
        [tktTimer invalidate];
        countDownlabel.text = @"Completed";
    }


}

任何帮助将不胜感激。

【问题讨论】:

    标签: ios objective-c iphone xcode nstimer


    【解决方案1】:

    --secondsLeft 更新变量。要检查下一个减量是否为 0,请使用 if (secondsLeft - 1 == 0)

    每个刻度都将变量递减两次。

    此外,这将在 1 而不是 0 上触发“已完成”文本。以下是处理此问题的更好方法:

    -(void) updateCountdown {
        int hours, minutes, seconds;
    
        secondsLeft--;
        if (secondsLeft == 0) {
            [tktTimer invalidate];
            countDownlabel.text = @"Completed";
            return;
        }        
        NSLog(@"secondsLeft %d",secondsLeft);//every time it is printing 9,7,5,3,1 but should print 9,8,7,6,5,4,3,2,1,0
        hours = secondsLeft / 3600;
        minutes = (secondsLeft % 3600) / 60;
        seconds = (secondsLeft %3600) % 60;
        countDownlabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];
    }
    

    【讨论】:

    • 如果我使用此 if 条件,那么我将面临使计时器无效的问题。您能否通过显示使计时器无效的代码来编辑您的答案。
    • 回顾代码以及它是如何工作的,这将触发“1”而不是“0” - 只是检查它是否为 0 会更好。我会更新我的答案。
    【解决方案2】:

    //用简单易懂的代码执行定时器的甜蜜和简单的方法

    声明

     int seconds;
     NSTimer *timer;
    

    //在viewDidLoad方法中

    seconds=12;
         timer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(GameOver) userInfo:nil repeats:YES ];
    
    -(void)GameOver
    {
         seconds-=1;
         lblUpTimer.text=[NSString stringWithFormat:@"%d",seconds];//shows counter in label
    
    if(seconds==0)
    [timer invalidate];
    }
    

    谢谢你

    【讨论】:

    • 虽然这显示了如何使用 scheduleTimer,但它并没有告诉 OP 问题是什么以及这对他/她有什么帮助。
    猜你喜欢
    • 1970-01-01
    • 2022-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-15
    相关资源
    最近更新 更多