首页 > 解决方案 > 每毫秒更新进度条

问题描述

我希望我的进度条每毫秒更新一次。我该怎么做?目前,它每秒更新一次,这不是我想要的。

编辑:对不起,我忘了提到我仍然希望计时器标签每秒更新一次(所以它会下降几秒而不是毫秒:10、9、8),同时每毫秒或每秒 25 次更新进度条。

代码:

 progressBar.transform = progressBar.transform.scaledBy(x: 1, y: 5)
        progressBar.layer.cornerRadius = 5
        progressBar.clipsToBounds = true
        progressBar.layer.sublayers![1].cornerRadius = 5
        progressBar.subviews[1].clipsToBounds = true

func startTimer() {

    timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerUpdate), userInfo: nil, repeats: true)

}

@objc func timerUpdate() {

    if timeRemaining <= 0 {
        progressBar.setProgress(Float(0), animated: false)
        bonusTimerLabel.text = "0"
        bonusTimerLabel.textColor = UIColor(red: 186/255, green: 16/255, blue: 16/255, alpha: 1)

    } else {
        progressBar.setProgress(Float(timeRemaining)/Float(10), animated: false)
        timeRemaining -= 1
        bonusTimerLabel.text = "\(timeRemaining)"
    }

标签: swiftprogress-bar

解决方案


timer不建议每毫秒触发一个函数,参考: https ://stackoverflow.com/a/30983444/8447312

因此,您可以每 50 毫秒触发一次计时器功能,以确保安全并更新您的进度条。不过,这不应该太明显。

还要确保timeRemaining是 a Double,然后尝试:

func startTimer() {

    timer = Timer.scheduledTimer(timeInterval: 0.050, target: self, selector: #selector(timerUpdate), userInfo: nil, repeats: true)

}

@objc func timerUpdate() {

    if timeRemaining <= 0 {
        progressBar.setProgress(Float(0), animated: false)
        bonusTimerLabel.text = "0"
        bonusTimerLabel.textColor = UIColor(red: 186/255, green: 16/255, blue: 16/255, alpha: 1)

    } else {
        progressBar.setProgress(Float(timeRemaining)/Float(20), animated: false)
        timeRemaining -= 0.050
        bonusTimerLabel.text = "\(Int(timeRemaining))"
    }

推荐阅读