简体   繁体   English

倒数计时器iphone sdk?

[英]Countdown timer iphone sdk?

I have a countdown timer in my game and I'm trying to figure out how to make it so that it shows two decimal places and records with 2 decimal places in my table. 我在我的游戏中有一个倒数计时器,我正在试图弄清楚如何使它显示两个小数位并在我的表中显示2位小数。 Right now it counts down as a whole number and records as a whole number. 现在它作为整数倒计时并记录为整数。 Any ideas? 有任何想法吗?

-(void)updateTimerLabel{

     if(appDelegate.gameStateRunning == YES){

                            if(gameVarLevel==1){
       timeSeconds = 100;
       AllowResetTimer = NO;
       }
    timeSeconds--;
    timerLabel.text=[NSString stringWithFormat:@"Time: %d", timeSeconds];
}

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

To have sub-second updates, the timer's interval needs to be < 1. But the precision of NSTimer is just around 50 ms, so scheduledTimerWithTimeInterval:0.01 will not work. 要进行亚秒级更新,计时器的间隔需要<1。但是NSTimer的精度只有大约50 ms,因此scheduledTimerWithTimeInterval:0.01将不起作用。

Moreover, the timer can be delayed by various activities, so using timeSeconds will lead to inaccurate timing. 此外,计时器可能会因各种活动而延迟,因此使用timeSeconds会导致计时不准确。 The usual way is compare the NSDate now with the date when the timer starts. 通常的方法是将NSDate现在与计时器启动的日期进行比较。 However, as this code is for a game, the current approach may cause less frustration to players esp. 但是,由于此代码适用于游戏,因此当前的方法可能会减少对玩家的挫败感。 if the program or background processes consumes lots of resources. 如果程序或后台进程消耗大量资源。


The first thing to do is to convert the countdownTimer to sub-second interval. 首先要做的是将countdownTimer转换为亚秒级间隔。

countdownTimer = [NSTimer scheduledTimerWithTimeInterval:0.67 target:self selector:@selector(updateTimerLabel) userInfo:nil repeats:YES];

Then, don't count down the time by seconds, but centiseconds: 然后,不要按秒计算时间,而是以厘秒为单位:

if(appDelegate.gameStateRunning == YES){
   if(gameVarLevel==1){
      timeCentiseconds = 10000;
      AllowResetTimer = NO;
   }
}
timeCentiseconds -= 67;

Finally, divide by 100 in the output: 最后,在输出中除以100:

timerLabel.text=[NSString stringWithFormat:@"Time: %d.%02d", timeCentiseconds/100, timeCentiseconds%100];

Alternatively, use a double : 或者,使用double

double timeSeconds;
...
if(appDelegate.gameStateRunning == YES){
   if(gameVarLevel==1){
      timeSeconds = 100;
      AllowResetTimer = NO;
   }
}
timeSeconds -= 0.67;
timerLabel.text=[NSString stringWithFormat:@"Time: %.2g", timeSeconds];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM