我在 View Controller 中有一个计时器,用它来检查函数。但是,如果我关闭设置了计时器的 View Controller ,它仍然会继续,或者如果时间达到零,我想自动关闭 View Controller 。就我现在的情况而言,如果我手动关闭 View Controller 而 View Controller 没有达到零,则时间仍然会继续,直到计数器达到 ero。
如何设置我的代码,以便如果我自己关闭 Viewcontroller,时间会停止并且不会达到零,以便我在时间为零时设置的条件不会运行。
下面是我的代码
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)
}
}
最佳答案
为计时器声明一个公共(public)变量,然后在您想要停止时使其无效。
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)
}
}
关于ios - 停止 View Controller 上的计时器解雇 swift ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54765801/