I am using Xcode with swift 3 to make a basic timer. I have a timer label connected to my view controller which updates the label every second. When timing for a longer period, the seconds run up faster (see GIF).
Can anyone explain what i am doing wrong, or what i should not be doing (wrong approach, better functions)?
This is the relevant code:
@IBAction func startButtonTabbed(_ sender: UIButton) {
if (sender == startButton) {
let now = Date()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
start_time = formatter.string(from:now)
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.timerAction), userInfo: nil, repeats: true)
} else {
timer.invalidate()
}
}
func timerAction() {
time += 1;
updateTimingLabel(seconds: time)
}
func updateTimingLabel(seconds: Int) {
self.timerLabel.text = stringFromTimeInterval(interval: TimeInterval(time)) as String
}
func stringFromTimeInterval(interval: TimeInterval) -> NSString {
let ti = NSInteger(interval)
let seconds = ti % 60
let minutes = (ti / 60) % 60
let hours = (ti / 3600)
return NSString(format: "%0.2d:%0.2d:%0.2d",hours,minutes,seconds)
}
This is what happens:
