1
我看过其他暂停/恢复计时器的问题,但无法弄清楚如何解决我的问题。我只有一个简单的计时器标签和两个按钮,一个开始和一个停止按钮。让我知道你是否需要关于我的项目的更多信息来帮助回答我的问题。任何人都可以看到我要去哪里吗?暂停后恢复定时器吗?
- (void)updateTimer
{
// Create date from the elapsed time
NSDate *currentDate = [NSDate date];
NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:self.startDate];
NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
// Create a date formatter
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"HH:mm:ss"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
// Format the elapsed time and set it to the label
NSString *timeString = [dateFormatter stringFromDate:timerDate];
self.stopwatchLabel.text = timeString;
}
- (void)updateResumeTimer
{
// Format the elapsed time and set it to the label
NSString *timeString = [dateFormat stringFromDate:dateFor];
self.stopwatchLabel.text = timeString;
}
- (IBAction)onStartPressed:(id)sender {
NSString *isItEqual = self.stopwatchLabel.text;
if ([isItEqual isEqualToString:@"00:00:00"]) {
self.startDate = [NSDate date];
// Create the stop watch timer that fires every 10 ms
self.stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/10.0
target:self
selector:@selector(updateTimer)
userInfo:nil
repeats:YES];
}
else {
// Create the stop watch timer that fires every 10 ms
self.stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/10.0
target:self
selector:@selector(updateResumeTimer)
userInfo:nil
repeats:YES];
}
}
- (IBAction)onStopPressed:(id)sender {
resumeText = self.stopwatchLabel.text;
NSLog(@"Timer is %@", resumeText);
dateFormat=[[NSDateFormatter alloc]init];
[dateFormat setDateFormat:@"HH:mm:ss"];
dateFor=[dateFormat dateFromString:resumeText];
[dateFormat setDateFormat:@"HH:mm:ss"];
[self.stopWatchTimer invalidate];
self.stopWatchTimer = nil;
[self updateTimer];
}
嗨,你提到有一个问题 - 你可以请包括在你的问题呢?你也可以通过意图增强计时器应该如何工作的问题。 – nzs
@codedad本质上,当我按停止,然后再次启动时,什么也没有发生,但如果我一直按下停止,那么你可以看到定时器仍然在后台运行,而不是暂停/停止和抓取定时器,定时器永远不会停止并始终继续在后台运行。 –