0

我试图让一个计时器来显示像这样“00:00:00”的计数器。这是我当前的代码。我一直在尝试使用 stringWithFormat 让它工作,这应该很容易,但我想我必须单独设置格式。你们对如何做到这一点有任何想法吗?

- (void)TimerCount {
    CountNumber = CountNumber + 1;
    TimerDisplay.text = [NSString stringWithFormat:@"Hour: %0*i", length, hour];
}
4

2 回答 2

1
- (void)timerCount {

 {
    CountNumber = CountNumber + 1;
    NSInteger seconds = CountNumber % 60;
    NSInteger minutes = (CountNumber / 60) % 60;
    NSInteger hours = (CountNumber / 3600);
    TimerDisplay.text =  [NSString stringWithFormat:@"%i:%02i:%02i", hours, minutes, seconds];
}

试试上面的代码。

并将此方法配置为每秒触发一次。

在 viewDidLoad

NSTimer *counterTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 
                                                        target:self 
                                                      selector:@selector(timerCount) 
                                                      userInfo:nil 
                                                       repeats:YES];
[[NSRunLoop mainRunLoop] addTimer: counterTimer forMode:NSRunLoopCommonModes];

如果您使用的是 ARC,请将 counterTimer 保持为 iVar 以使其保持活动状态,直到 VC 被释放。

于 2014-04-03T11:09:18.263 回答
-1
- (void)TimerCount
{
    CountNumber++;
    NSString *time = [[NSString alloc] init];
    NSUInteger seconds = CountNumber;
    NSUInteger minutes = 0;
    NSUInteger hours = 0;
    if (seconds > 59) {
        seconds -= 60;
        minutes++;
        if (seconds < 10) {
            time = [NSString stringWithFormat:@":0%i",seconds];
        } else time = [NSString stringWithFormat:@":%i",seconds];
    }
    if (minutes > 59) {
        minutes -= 60;
        hours++;
        if (minutes < 10) {
            time = [NSString stringWithFormat:@":0%i%@",minutes,time];
        } else time = [NSString stringWithFormat:@":%i%@",minutes,time];
    }
    if (hours < 10) {
        time = [NSString stringWithFormat:@"0%i%@",hours,time];
    } else time = [NSString stringWithFormat:@"%i%@",hours,time];

}

NSString *time 是时间。

还有 NSTimer 每秒调用这个方法:

NSTimer *counterTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 
                                                        target:self 
                                                      selector:@selector(timerCount) 
                                                      userInfo:nil 
                                                       repeats:YES];
于 2014-04-03T10:26:08.767 回答