无法通过在 Swift 中将布尔值更改为 false 来停止计时器
Unable to stop the Timer by changing the Boolean value to false in Swift
我尝试了运行下面的代码,但是计时器在计数到“0”秒后不会停止。
Desired OutPut : 5 seconds. 4 seconds. 3 seconds. 2 seconds. 1
seconds. 0 seconds.
class ViewController: UIViewController {
var seconds = 5
var value = true
@IBAction
func buttonPressed(_ sender: UIButton) {
Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(secondsRemaining), userInfo: nil, repeats: value)
}
@objc
func secondsRemaining() {
print("\(seconds) seconds.")
if seconds > 0{
seconds -= 1
}else{
value = false
}
}
}
当您安排一个计时器将 true
作为 repeats
传递时,这意味着该计时器将继续发生,除非您在返回实例上显式调用 invalidate()
函数并将其设置为nil
.
所以,您的代码应该是这样的:
class ViewController: UIViewController {
var seconds = 5
var timer: Timer?
@IBAction func buttonPressed(_ sender: UIButton) {
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(secondsRemaining), userInfo: nil, repeats: true)
}
@objc func secondsRemaining() {
print("\(seconds) seconds.")
if seconds > 0 {
seconds -= 1
} else {
timer?.invalidate()
timer = nil
}
}
}
我尝试了运行下面的代码,但是计时器在计数到“0”秒后不会停止。
Desired OutPut : 5 seconds. 4 seconds. 3 seconds. 2 seconds. 1 seconds. 0 seconds.
class ViewController: UIViewController {
var seconds = 5
var value = true
@IBAction
func buttonPressed(_ sender: UIButton) {
Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(secondsRemaining), userInfo: nil, repeats: value)
}
@objc
func secondsRemaining() {
print("\(seconds) seconds.")
if seconds > 0{
seconds -= 1
}else{
value = false
}
}
}
当您安排一个计时器将 true
作为 repeats
传递时,这意味着该计时器将继续发生,除非您在返回实例上显式调用 invalidate()
函数并将其设置为nil
.
所以,您的代码应该是这样的:
class ViewController: UIViewController {
var seconds = 5
var timer: Timer?
@IBAction func buttonPressed(_ sender: UIButton) {
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(secondsRemaining), userInfo: nil, repeats: true)
}
@objc func secondsRemaining() {
print("\(seconds) seconds.")
if seconds > 0 {
seconds -= 1
} else {
timer?.invalidate()
timer = nil
}
}
}