I'm a newbie in swift and I tried to make a Timer. It should normally count the seconds and print them in the debugger.
I tried this:
var timer = Timer()
@IBAction func killTimer(_ sender: AnyObject) {
timer.invalidate()
}
@objc func processTimer() {
print("This is a second")
}
override func viewDidLoad() {
super.viewDidLoad()
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.processTimer), userInfo: nil, repeats: true)
}
I don't know how the timer count seconds.. With this code i get an fail message:
@objc func processTimer() {
print("This is second \(Timer + 1)")
}
Thanks for your help. A
You need a counter variable which is incremented every time the timer fires.
Declare the variable Timer
as optional to invalidate the timer reliably (only once).
var timer : Timer?
var counter = 0
@IBAction func killTimer(_ sender: AnyObject) {
timer?.invalidate()
timer = nil
}
@objc func prozessTimer() {
counter += 1
print("This is a second ", counter)
}
override func viewDidLoad() {
super.viewDidLoad()
timer = Timer.scheduledTimer(timeInterval:1, target:self, selector:#selector(prozessTimer), userInfo: nil, repeats: true)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With