我正在开发一个游戏项目。我需要知道如何显示游戏开始到游戏结束的秒数?还需要以“00:01”的格式显示。另外,如果时间超过 60 分钟,还应该显示小时“1:00:01”
有什么指导吗?
谢谢...
最佳答案
结合 Nathan 和 Mark 的答案后,完整的计时器方法可能如下所示:
- (void)timer:(NSTimer *)timer {
NSInteger secondsSinceStart = (NSInteger)[[NSDate date] timeIntervalSinceDate:startDate];
NSInteger seconds = secondsSinceStart % 60;
NSInteger minutes = (secondsSinceStart / 60) % 60;
NSInteger hours = secondsSinceStart / (60 * 60);
NSString *result = nil;
if (hours > 0) {
result = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];
}
else {
result = [NSString stringWithFormat:@"%02d:%02d", minutes, seconds];
}
// set result as label.text
}
当您开始游戏时,您可以设置开始日期并启动计时器,如下所示:
self.startDate = [NSDate date];
timer = [NSTimer scheduledTimerWithTimeInterval:0.25 target:self selector:@selector(timer:) userInfo:nil repeats:YES];
停止游戏时,您可以使用以下命令:
self.startDate = nil;
[timer invalidate];
timer = nil;
关于iphone - 如何使用ntimer显示秒?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6152963/