-
Notifications
You must be signed in to change notification settings - Fork 0
/
Timer.Swift
46 lines (33 loc) · 1.08 KB
/
Timer.Swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var timerLabel: UILabel!
var countdownTimer: Timer!
var totalTime = 60 // In Sec
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
func startTimer() {
countdownTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
}
func updateTime() {
timerLabel.text = "\(timeFormatted(totalTime))"
if totalTime != 0 {
totalTime -= 1
} else {
endTimer()
}
}
func endTimer() {
countdownTimer.invalidate()
}
func timeFormatted(_ totalSeconds: Int) -> String {
let seconds: Int = totalSeconds % 60
let minutes: Int = (totalSeconds / 60) % 60
// let hours: Int = totalSeconds / 3600
return String(format: "%02d:%02d", minutes, seconds)
}
@IBAction func startTimerPressed(_ sender: UIButton) {
startTimer()
}
}