Mau*_*lik 2 iphone objective-c nstimer
我正在开发一个游戏项目.我需要知道如何在游戏开始到游戏结束时显示秒数?还需要以"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
}
Run Code Online (Sandbox Code Playgroud)
当你开始游戏时,你设置startDate并启动计时器,如下所示:
self.startDate = [NSDate date];
timer = [NSTimer scheduledTimerWithTimeInterval:0.25 target:self selector:@selector(timer:) userInfo:nil repeats:YES];
Run Code Online (Sandbox Code Playgroud)
停止游戏时你使用这个:
self.startDate = nil;
[timer invalidate];
timer = nil;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3174 次 |
| 最近记录: |