這是一個常見問題,但大多數答案似乎不起作用。我在我的應用程序中有一個計時器,我可以輕鬆啓動並重新啓動計時器。我正在嘗試暫停並恢復計時器,但現在只能繼續計時器的計時器,而計時器的計時器大於恢復的時間。這可能意味着它在後臺繼續計數。這是我的代碼:在iOS中暫停和恢復計時器
//Timer Variables
var startTime = NSTimeInterval()
var timer = NSTimer()
var isTiming = Bool()
var isPaused = Bool()
func updatedTimer() {
let currentTime = NSDate.timeIntervalSinceReferenceDate()
var elapsedTime: NSTimeInterval = currentTime - startTime
let minutes = UInt8(elapsedTime/60.0)
elapsedTime -= (NSTimeInterval(minutes) * 60)
let seconds = UInt8(elapsedTime)
elapsedTime -= NSTimeInterval(seconds)
let strMinutes = String(format: "%02d", minutes)
let strSeconds = String(format: "%02d", seconds)
workoutTime.text = "\(strMinutes) : \(strSeconds)"
}
@IBAction func startButtonTapped(sender: AnyObject) {
if !timer.valid {
timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: #selector(TimedWorkoutViewController.updatedTimer), userInfo: nil, repeats: true)
startTime = NSDate.timeIntervalSinceReferenceDate()
}
isTiming = true
isPaused = false
}
@IBAction func pauseAndContinueButtonTapped(sender: AnyObject) {
if isTiming == true && isPaused == false {
timer.invalidate() //Stop the Timer
isPaused = true //isPaused
isTiming = false //Stopped Timing
pauseButton.setTitle("RESUME", forState: UIControlState.Normal) //Set Button to Continue state
print(startTime)
} else if isTiming == false && isPaused == true {
if !timer.valid {
timer.invalidate()
//timer = nil
timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: #selector(TimedWorkoutViewController.updatedTimer), userInfo: nil, repeats: true)
}
isPaused = false
isTiming = true
pauseButton.setTitle("PAUSE", forState: UIControlState.Normal) //Set Button to Continue state
}
}
你介意分享你的代碼,如果你還有嗎? – Gugulethu
太棒了。完美工作。非常感謝。 – Gugulethu
因此,在說'pausedIntervals.append(pausedSeconds)'的行上,我得到以下錯誤:'無法將類型'(Date) - > TimeInterval'的值轉換爲期望的參數類型'TimeInterval'(又名'Double')' 任何想法爲什麼?幾次谷歌搜索仍然沒有。 –