我正在創建計時器,格式爲HH:mm,但現在我的問題是暫停計時器並恢復計時。現在,當您暫停計時器時,它會繼續在後臺計數,但可見部分已停止。一旦你點擊恢復按鈕,計時器就會更新到它離開的地方,在暫停多久之前,計時器可能會超出應有的數量。例如,如果計時器計數到5,那麼暫停計時器,現在坐在5,一旦你點擊繼續,計時器可能會從15開始,因爲它已經停止了10秒。下面是我的代碼,我從幾個地方相結合,得到這個工作:即使定時器在視覺上已停止,NSTimer仍會繼續計數
- (void) createTimerPage
{
_dateFormat = [NSDate date];
// Add pause button
UIImage *pause = [UIImage imageNamed:@"pause.png"];
_pauseBtn = [UIButton buttonWithType:UIButtonTypeCustom];
_pauseBtn.frame = CGRectMake(151, 17, 32, 32);
[_pauseBtn addTarget:self action:@selector(pauseTimer) forControlEvents:UIControlEventTouchUpInside];
[_pauseBtn setBackgroundImage:pause forState:UIControlStateNormal];
}
- (void) startTimer
{
// Start timer
NSInteger secondsSinceStart = (NSInteger) [[NSDate date] timeIntervalSinceDate:_dateFormat];
NSInteger seconds = secondsSinceStart % 60;
NSInteger minutes = (secondsSinceStart/60) % 60;
NSString *result = nil;
result = [NSString stringWithFormat:@"%02d:%02d", minutes, seconds];
_timerText.text = result;
[_timerBtns addSubview:_pauseBtn];
}
- (void) startPressed
{
[_time invalidate];
_time = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(startTimer)
userInfo:nil
repeats:YES];
}
- (void) pauseTimer
{
if (_time) {
// pause timer
[_time invalidate];
[_timerBtns addSubview:_playBtn];
}
}
看,上面寫着secondsSinceStart =行[NSDate的日期] timeIntervalSinceDate:_dateFormat。當用戶啓動,暫停,然後恢復計時器時,secondsSinceStart的值是多少? – rocky