我正在使用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";
}
}
任何帮助都将非常感激。
答案 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];
}
谢谢你