这是我的iPhone秒表应用程序的代码,当你点击开始按钮时,它将以正确的格式计数,所有工作正常,以及停止按钮和重置。问题是每次我点击停止,然后再次开始它创建一个新的计时器,不继续从最后一个。我如何创建暂停并能够从当前时间继续?
感谢NSDate *startDate;
NSTimer *stopWatchTimer;
-(void)showActivity {
NSDate *currentDate = [NSDate date];
NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate];
NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"mm:ss.SS"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
NSString *timeString=[dateFormatter stringFromDate:timerDate];
stopWatchLabel.text = timeString;
[dateFormatter release];
}
- (IBAction)onStartPressed:(id)sender {
startDate = [[NSDate date]retain];
stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1/10 target:self selector:@selector(showActivity) userInfo:nil repeats:YES];
}
- (IBAction)onStopPressed:(id)sender {
[stopWatchTimer invalidate];
stopWatchTimer = nil;
[self showActivity];
}
- (IBAction)reset:(id)sender; {
stopWatchLabel.text = @"00:00.00";
}
在Pause期间,您可能希望将timeInterval保留为iVar
accumulatedInterval = [currentDate timeIntervalSinceDate:startDate];
不要在每次开始时都设置startDate。只在第一次重置之后。