I have a timer in a view controller which I use to check a function. How ever, If I dismiss the Viewcontroller where the timer is set, it still continues or if the time reaches zero, I want to automatically dismiss the viewcontroller. In my case now, if I dismiss the viewcontroller manually without the viewcontroller reaching zero, the time still continues till the counter reaches ero.
how can I set my code such that if I dismiss the Viewcontroller myself, the time stops and not reach zero so that the condition I put if the time is zero does not run.
below is my code
override func viewDidLoad() {
super.viewDidLoad()
var _ = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateCounter), userInfo: nil, repeats: true)
timerLabel.text = "\(counter)"
}
@objc func updateCounter() {
//you code, this is an example
if counter >= 0 {
timerLabel.text = "\(counter)"
counter -= 1
}
if counter == 0 {
Print.HOMEPRINT("COUNTER GOT TO ZERO")
dismiss(animated: true, completion: nil)
}
}
declare a public variable for timer and then invalidate it when you want to stop.
var timer : Timer?
override func viewDidLoad() {
super.viewDidLoad()
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateCounter), userInfo: nil, repeats: true)
timerLabel.text = "\(counter)"
}
@objc func updateCounter() {
//you code, this is an example
if counter >= 0 {
timerLabel.text = "\(counter)"
counter -= 1
}
if counter == 0 {
timer?.invalidate()
Print.HOMEPRINT("COUNTER GOT TO ZERO")
dismiss(animated: true, completion: nil)
}
}
Create a global variable for Timer
var myTimer : Timer?
override func viewDidLoad() {
super.viewDidLoad()
myTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateCounter), userInfo: nil, repeats: true)
timerLabel.text = "\(counter)"
}
@objc func updateCounter() {
//you code, this is an example
if counter >= 0 {
timerLabel.text = "\(counter)"
counter -= 1
}
if counter == 0 {
if (myTimer != nil)
{
myTimer?.invalidate()
myTimer = nil
}
Print.HOMEPRINT("COUNTER GOT TO ZERO")
dismiss(animated: true, completion: nil)
}
}
//MARK: Manually dismiss controller
@objc func dismissButtonTapped()
{
if (myTimer != nil)
{
myTimer?.invalidate()
myTimer = nil
}
dismiss(animated: true, completion: nil)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.