我想制作一个计时器,它可以通过一个按钮触发来启动计时器。当计时器运行时,我想要同一个按钮来暂停计时器。
我主要在按钮标签的 IBAction 中处理此行为:
@IBAction func btn_start(_ sender: Any) {
if timerIsRunning == false {
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(runTimer), userInfo: nil, repeats: true)
timerIsRunning = true
}
if timerIsRunning == true {
timer.invalidate()
timerIsRunning = false
}
}
我意识到我可以多次触发开始按钮并且计时器也被触发了几次,所以计时器最终会加速。 为了防止这种行为,我引入了 timerIsRunning:Bool 并产生了意想不到的结果,即计时器不再启动 :-/
这是我的计时器函数,由计时器触发:
func runTimer() {
if timeInSeconds >= 0 {
timeInSeconds = timeInSeconds - 1
updateTimerLabel()
}
}
谁能解释一下?帮我一把?
最佳答案
您应该在启动计时器后return
,或者使用else
。否则,您总是会在您的方法中的第二个 if
block 中立即使
新创建的计时器:
@IBAction func btn_start(_ sender: Any) {
if !timerIsRunning {
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(runTimer), userInfo: nil, repeats: true)
timerIsRunning = true
} else {
timer.invalidate()
timerIsRunning = false
}
}
关于swift - 计时器不会从开始/暂停切换按钮开始,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45700193/