-3

我创建了一个从 10 到 0 的倒数计时器。我创建了一个以秒为单位显示计数器的 uilabel。现在我希望标签显示计数器分钟和秒,就像这样:00:00。我怎样才能做到这一点?这是我的倒计时代码:

-(void)countdown
{
    countdownCounter -= 1;
    countdown.text = [NSString stringWithFormat:@"%i", countdownCounter];

}

-(IBAction)strat:(id)sender
{
    countdownCounter = 10;
    countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self     selector:@selector(countdown) userInfo:nil repeats:YES];
    }

}

谢谢!

4

4 回答 4

3

这可以使用一次和一个标签来完成。尝试使用以下代码:

int seconds = [countDown.text intValue] % 60; 
int minutes = ([countDown.text intValue] / 60) % 60; 
countDown.text = [NSString stringWithFormat:@"%2d:%02d", minutes, seconds]; 
于 2012-06-25T20:20:49.893 回答
2

以完全相同的方式进行操作,只需添加另一个计时器。

  countdownTimer2 = [NSTimer scheduledTimerWithTimeInterval:60.0 target:self selector:@selector(countdown2) userInfo:nil repeats:YES];

-(void)countdown2
{
    countdownCounterMinutes -= 1;
}

and change countdown to

-(void)countdown
{
    countdownCounter -= 1;
    countdown.text = [NSString stringWithFormat:@"%i%i", countdownCounterMinutes, countdownCounter];

}
于 2012-06-25T18:13:07.240 回答
1

对于任何最终答案是什么的人,我都是这样做的:

-(IBAction)start
{
    timer = [NSTimer scheduledTimerWithTimeInterval:.01 target:self     selector:@selector(updateTimer:) userInfo:nil repeats:YES];
}

-(void)updateTimer:(NSTimer *)timer {
    currentTime -= 10 ;
    [self populateLabelwithTime:currentTime];
    if(currentTime <=0)
       [timer invalidate];
}


- (void)populateLabelwithTime:(int)milliseconds {
    seconds = milliseconds/1000;
    minutes = seconds / 60;
    hours = minutes / 60;

    seconds -= minutes * 60;
    minutes -= hours * 60;

    NSString * result1 = [NSString stringWithFormat:@"%@%02d:%02d:%02d:%02d", (milliseconds<0?@"-":@""), hours, minutes, seconds,milliseconds%1000];
    result.text = result1;

}

在 viewDidLoad 我将 currentTime 设置为以毫秒为单位的倒计时时间。希望你能理解...

于 2012-06-26T17:05:23.753 回答
0

我用这种方式用分钟和秒格式化了数字(来自浮点数),谢谢你的回答。(希望这有助于另一个)

   - (void)ticTimer
{
    self.current -= self.updateSpeed;
    CGFloat progress = self.current / self.max;
    [self populateLabelwithTimeFormatted:self.current];
     ///  TimeLabelNode.text = [NSString stringWithFormat:@"%f", progress];

    // * Time is over
    if (self.current <= self.min) {
        [self stop];
        _TimeLabelNode.text= @"time up!";
    }
}

- (void)populateLabelwithTimeFormatted:(float)time {
    //convert float into mins and seconds format
    int mytime = (int) _current;
    int seconds = mytime%60;
    int minutes = mytime / 60 % 60;

    NSString * result1 = [NSString stringWithFormat:@"%2d:%02d",  minutes, seconds];
    _TimeLabelNode.text = result1;
}
于 2016-10-29T10:23:44.580 回答