这是我的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";
}
答案 0 :(得分:1)
在暂停期间,您可能希望将timeInterval保留到iVar中
cumulativeInterval = [currentDate timeIntervalSinceDate:startDate];
并一直添加到timeInterval。
答案 1 :(得分:0)
每次开始按下都不要设置startDate。只是第一次,并在重置之后。布尔状态变量可以帮助跟踪。