ios - 计时器倒计时中未显示的所有数字
问题描述
在进入视图时,我调用一个函数来加载一个像这样的计时器......
var count = 10
func startTimer() {
timer = Timer.scheduledTimer(timeInterval: 0.4, target: self, selector: #selector(self.update), userInfo: nil, repeats: true)
}
并且update
功能被给出为..
@objc func update() {
while (count != 0) {
count -= 1
countdownLabel.text = "\(count)"
}
timer.invalidate()
}
但是当我看到这个视图时,会直接显示数字 0,而不是理想地显示序列 9、8、7、6、5、4、3、2、1、0 中的所有数字
我在这里做错了什么..?
解决方案
斯威夫特 4:
var totalTime = 10
var countdownTimer: Timer!
@IBOutlet weak var timeLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
startTimer()
}
此方法调用初始化计时器。它指定 timeInterval(调用 a 方法的频率)和选择器(调用的方法)。
间隔以秒为单位,因此要让它像标准时钟一样运行,我们应该将此参数设置为 1。
func startTimer() {
countdownTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
}
// Stops the timer from ever firing again and requests its removal from its run loop.
func endTimer() {
countdownTimer.invalidate()
}
//updateTimer is the name of the method that will be called at each second. This method will update the label
@objc func updateTime() {
timeLabel.text = "\(totalTime)"
if totalTime != 0 {
totalTime -= 1
} else {
endTimer()
}
}
推荐阅读
- python - 使用 python 发送 zip 文件(创建专用服务器和客户端)以克隆流行平台,如使用 python 中的套接字的 Steam
- java - openssl_encrypt aes 256 与 java 中的哈希
- javascript - 2个文本框在键入时相互复制值,但另一个文本框没有逗号
- python - 这段代码可以提高效率吗?它不适用于更大的输入
- itext7 - iText7 pdfSweep 编辑超出预期
- gstreamer - 关于 gst-rtsp-server 和 g_main_loop 的一些问题
- typescript - 如何强制字段在对象打字稿中
- reactjs - 使用 div 渲染元素(绝对位置、顶部、右侧、底部、左侧),获取 de screenPositions 以了解渲染位置。如何听滚动?
- python - 使用break时在python生成器中的yield语句之后运行代码
- python - Python 请求未捕获 Internet 断开连接