ios - 斯威夫特 | 计时器不会在无效呼叫时停止,而是加快速度?
问题描述
我在这个应用程序中使用计时器制作了一个秒表,并添加了开始停止按钮来暂停和播放相同的内容。当按下按钮时,它被发送到一个使定时器无效的函数,它应该停止。 但奇怪的是,当按下停止按钮时,而不是停止计时器以某种方式加速 我没有改变时间间隔,只是宣布它一次。
我试图在按下开始按钮后禁用它,甚至隐藏它。还尝试更改时间间隔,但没有任何效果。我按下开始停止按钮的次数越多,它就越加速并且开始比提到的时间间隔快得多。
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)
}
解决方案
尝试通过隐藏停止按钮同时添加两个按钮,然后在按钮单击时隐藏和取消隐藏按钮。当您尝试停止计时器时,您的播放按钮方法每次都在运行
推荐阅读
- node.js - What is the `PM2` for command `yarn run start`?
- xml - 使用 xslt 来自特定节点类型的 XML 到 csv
- angular - Angular6 & tinyMCE 编辑器
- if-statement - 带有检索和变量的 sparql 查询 if 语句
- php - 如何将图像名称保存在数据库中以便以后查看?
- excel - 删除 VBA 工作表中提到的多个变量列
- php - 在验证用户与 Symfony 4 和 FOSUserBundle 连接后重定向用户
- jsf - ui:repeat 中的复合组件:如何正确保存组件状态
- sql - SQL WHERE 子句从多个列中过滤
- java - 如何从java中的字节数组中获取整数数组并打印输出数组?字节数组来自 225*225 维度的灰度图像