[Swift]: Add Live Timer on Controller

swift

05/07/2019


Adding a live timer in Swift 5

1) Create a label

SWIFT
@IBOutlet weak var timeLapse: UILabel!

2) Make other instance variables

SWIFT
// Timer
var timer = Timer()
var seconds = 0

3) Create functions to start the timer

SWIFT
func startTimer() {
// Time interval: frequency of method called. 1: every sec
// selector: method being called
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: (#selector(self.updateTimer)), userInfo: nil, repeats: true)
}
@objc
func updateTimer() {
seconds += 1
timeLapse.text = "\(seconds)"
}

Once startTime() is called, it will call updateTimer() every second

3) Call the implemented func from a button to start to timer:

SWIFT
@IBAction func restartGame() {
// Reset the timer
timer.invalidate()
seconds = 0
timeLapse.text = formatTime(time: TimeInterval(seconds))
startTimer()
}

Since the Concentration game needs a restart on a new game button or after fininshing a game, it needs to invalidate() the timer. Otherwise, there will be a multiple timers running at the same time, increasing multiple seconds per second.

4) Format time

So far, the timeLapse label only has a text that increases from initial seconds = 0 to seconds += 1 per second. It needs a formatting

SWIFT
func formatTime(time: TimeInterval) -> String {
let minutes = Int(time) / 60 % 60
let seconds = Int(time) % 60
return String(format:"%02i:%02i", minutes, seconds)
}

Now, back to 3) to update the formated time. Change

SWIFT
@objc
func updateTimer() {
seconds += 1
timeLapse.text = "\(seconds)"
}

to

SWIFT
@objc
func updateTimer() {
seconds += 1
timeLapse.text = formatTime(time: TimeInterval(seconds))
}

WRITTEN BY

Keeping a record