我希望进度条每毫秒更新一次。我该怎么做?目前,它每秒更新一次,这不是我想要的。
编辑:对不起,我忘了提及我仍然希望计时器标签每秒更新一次(因此它将下降几秒钟而不是毫秒: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)"
}
答案 0 :(得分:0)
不建议每毫秒用timer
启动一个函数,请参考:https://stackoverflow.com/a/30983444/8447312
因此,您可以每50毫秒触发一次计时器函数,以确保安全并更新进度条。不过,这应该不太明显。
还要确保timeRemaining
是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))"
}
答案 1 :(得分:0)
1毫秒是0.001秒。 因此,将计时器中的timerInterval属性更改为0.001:
timer = Timer.scheduledTimer(timeInterval: 0.001, target: self, selector: #selector(timerUpdate), userInfo: nil, repeats: true)