nstimer倒计时未按预期工作

时间:2016-11-22 11:46:36

标签: ios objective-c iphone xcode nstimer

我正在使用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";
    }


}

任何帮助都将非常感激。

2 个答案:

答案 0 :(得分:3)

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

每个tick都会将变量递减两次。

此外,这将触发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];
}

答案 1 :(得分:-1)

//用简单易懂的代码执行计时器的简单方法

DECLARE

 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];
}

谢谢你