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本質上,當我按停止,然後再次啓動時,什麼也沒有發生,但如果我一直按下停止,那麼你可以看到定時器仍然在後臺運行,而不是暫停/停止和抓取定時器,定時器永遠不會停止並始終繼續在後臺運行。 –