我正在尝试将UILabel设置为从0%变为(插入数字)%,并在1秒的持续时间内显示其间的每个数字。
直到现在我都失败了,我疯了: - )
我甚至没有把它设置到我可以设置持续时间的部分。到目前为止我做了什么(并且失败了)是这样的:
var current: Int = Int(0.0 * 100)
let endValue: Int = Int(toValue * 100)
if current < endValue {
self.progressLabel.text = "\(current)%"
current += Int(0.01 * 100)
}
toValue
是调用函数时接收的Double。
任何帮助都会很棒!
编辑:
我使用此代码在uilabel中显示正确的endValue
,并在viewDidLoad之前向上移动var current...
。问题是现在它没有显示progressLabel.text
中当前和endValue之间的数字..
while current <= endValue {
self.progressLabel.text = "\(current)%"
current = current + Int(0.01 * 100)
}
答案 0 :(得分:1)
这是一个不依赖于计时器的函数,而是使用GCD中的DispatchQueue
asyncAfter
方法。
func updateCounter(currentValue: Int, toValue: Double) {
if currentValue <= Int(toValue * 100) {
progressLabel.text = "\(currentValue)%"
let dispatchTime: DispatchTime = DispatchTime.now() + Double(Int64(1.0 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: dispatchTime, execute: {
self.updateCounter(currentValue: currentValue + 1, toValue: toValue)
})
}
}
用它调用它将产生0-10的计数:
updateCounter(currentValue: 0, toValue: 0.1)
答案 1 :(得分:0)
您最近更新的代码中存在的问题是,每次更改电流时,您的程序都不会更新UILabel。 while循环将继续,直到当前到达为最终值,然后您的UILabel将更新一次。
在这个答案中引用了什么可能会帮助你使用计时器:
How to make a countdown with NSTimer on Swift
创建一个方法,将UILabel的当前值增加1,然后使用计时器每秒调用一次该方法。