When I hit Pause it pauses the timer. but then when I hit start, it resets to 0 instead of continue where it left off. How can I fix this?
I've tried adding a new button for reset. that works, but now I can't get the start button to keep counting after a pause. I've been struggling with getting the resume to work.
import UIKit
class TimerViewController: UIViewController {
@IBOutlet weak var lable: UILabel!
@objc var startTime = TimeInterval()
var timer = Timer()
override func viewDidLoad(){
super.viewDidLoad()
}
// Start Button
@IBAction func start(_ sender: UIButton) {
if (!timer.isValid) {
let aSelector = #selector(updateTime)
timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: aSelector, userInfo: nil, repeats: true)
startTime = NSDate.timeIntervalSinceReferenceDate
}
}
// Pause Button
@IBAction func pause(_ sender: UIButton)
{
timer.invalidate()
}
// Reset Button
@IBAction func reset(_ sender: UIButton)
{
timer.invalidate()
lable.text = "00:00:00"
}
@objc func updateTime() {
let currentTime = NSDate.timeIntervalSinceReferenceDate
//Find the difference between current time and start time.
var elapsedTime: TimeInterval = currentTime - startTime
//calculate the minutes in elapsed time.
let minutes = UInt8(elapsedTime / 60.0)
elapsedTime -= (TimeInterval(minutes) * 60)
//calculate the seconds in elapsed time.
let seconds = UInt8(elapsedTime)
elapsedTime -= TimeInterval(seconds)
//find out the fraction of milliseconds to be displayed.
let fraction = UInt8(elapsedTime * 100)
//add the leading zero for minutes, seconds and millseconds and store them as string constants
let strMinutes = String(format: "%02d", minutes)
let strSeconds = String(format: "%02d", seconds)
let strFraction = String(format: "%02d", fraction)
//concatenate minuets, seconds and milliseconds as assign it to the UILabel
lable.text = "\(strMinutes):\(strSeconds):\(strFraction)"
}
}