首页 > 解决方案 > 斯威夫特 | 计时器不会在无效呼叫时停止,而是加快速度?

问题描述

我在这个应用程序中使用计时器制作了一个秒表,并添加了开始停止按钮来暂停和播放相同的内容。当按下按钮时,它被发送到一个使定时器无效的函数,它应该停止。 但奇怪的是,当按下停止按钮时,而不是停止计时器以某种方式加速 我没有改变时间间隔,只是宣布它一次。

我试图在按下开始按钮后禁用它,甚至隐藏它。还尝试更改时间间隔,但没有任何效果。我按下开始停止按钮的次数越多,它就越加速并且开始比提到的时间间隔快得多。

startButton.frame = CGRect(x: 0, y: UIScreen.main.bounds.height * 0.9 , width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height * 0.1)
    startButton.setTitle("Start Timer", for: .normal)
    self.view.addSubview(startButton)
    startButton.setTitleColor(.white , for: .normal)
    startButton.backgroundColor = .red
    startButton.addTarget(self, action: #selector(playButton(_:)), for: .allTouchEvents)

    stopButton.frame = CGRect(x: 0, y: UIScreen.main.bounds.height * 0.9 , width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height * 0.1)
    stopButton.setTitle("Stop Timer", for: .normal)
    stopButton.setTitleColor(.white , for: .normal)
    stopButton.backgroundColor = .red
    stopButton.addTarget(self, action: #selector(pauseButton(_:)), for: .allTouchEvents)
@objc func playButton(_ sender : Any)
{
    timer = Timer.scheduledTimer(timeInterval: 1, target: self , selector: #selector(updateTimer), userInfo: nil, repeats: true)
    startButton.isEnabled = false
    stopButton.isEnabled = true
    isRunning = true
    self.view.addSubview(stopButton)
    startButton.isHidden = true
    stopButton.isHidden = false



}

@objc func pauseButton(_ sender: Any) {
    self.view.addSubview(startButton)
    timer.invalidate()

    stopButton.isHidden = true
    startButton.isHidden = false

    startButton.isEnabled = true
    stopButton.isEnabled = false

    isRunning = false

}


@objc func updateTimer(_ sender : Any)
{
    counter += 0.1
    titleLabel.text = String(format: "%.1f", counter)
}

标签: iosswiftuibuttonnstimerstopwatch

解决方案


尝试通过隐藏停止按钮同时添加两个按钮,然后在按钮单击时隐藏和取消隐藏按钮。当您尝试停止计时器时,您的播放按钮方法每次都在运行


推荐阅读