【发布时间】:2014-10-27 14:01:54
【问题描述】:
我正在编写一个基本的 hh:mm:ss 计时器应用程序。我的计时器在开始、暂停和停止选项中都能完美运行。我的问题是当我在应用程序上交换屏幕时,计时器停止并返回到 00:00:00。
我是否需要将它保存在一个无论如何都会更新的数组中?有没有我可以实现的方法或教程可以让计时器连续计数,即使我交换屏幕、转到另一个应用程序或屏幕休眠?
任何想要实现计时器的人的代码:
//==================开始工作计时器=======================//
//Work Timer
- (void)updateWorkTimer {
if(working == false) return;
//calculate elapsed time
NSTimeInterval currentTime = [NSDate timeIntervalSinceReferenceDate];
NSTimeInterval elapsed = workSecondsAlreadyRun + currentTime - startWorkTime;
// extract out the minutes, seconds, and hours of seconds from elapsed time:
int hours = (int)(mins / 60.0);
elapsed -= hours * 60;
int workingMins = (int)(elapsed / 60.0);
elapsed -= workingMins * 60;
int secs = (int) (elapsed);
//update our label using the format of 00:00:00
self.workTimerLabel.text = [NSString stringWithFormat:@"%02u:%02u:%02u", hours, workingMins, secs];
//call updateTime every 1 second
[self performSelector:@selector(updateWorkTimer) withObject:self afterDelay:1];
}
//=============================================== ==================================================== ===================
- (IBAction)startWorkButton:(id)sender {
if(working == false) {
//start timer
working = true;
startWorkDate = [[NSDate alloc] init];
startWorkTime = [NSDate timeIntervalSinceReferenceDate];
//Set color and title for the button
[self.startWorkButton setBackgroundColor:[UIColor blueColor]];
[sender setTitle:@"Pause Work" forState:UIControlStateNormal];
[self updateWorkTimer];
}
else {
//pause timer
workSecondsAlreadyRun += [[NSDate date] timeIntervalSinceDate:startWorkDate];
startWorkDate = [[NSDate alloc] init];
//Set color and title for the button
UIColor * color = [UIColor colorWithRed:56/255.0f green:171/255.0f blue:10/255.0f alpha:1.0f];
[self.startWorkButton setBackgroundColor: color ];
[sender setTitle:@"Resume Work" forState:UIControlStateNormal];
working = false;
}
}
提前致谢。
【问题讨论】:
-
也附上你的计时器代码..
-
@raki 我已附上。这对可能的解决方案有帮助吗?
标签: ios iphone xcode ipad timer