本文介绍了Swift:延迟增加标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我的应用程序到达这部分代码时,它会冻结.我试图以半秒的延迟增加一个数字,然后将其打印到屏幕上.所以标签文本会变成 1,然后是 2,然后是 3,等等.我把这段代码扔到了操场上,DispatchQueue 似乎无限上升.谢谢.
My app freezes when it reaches this part of the code. I am attempting to increment a number with a half of a second delay, then printing that to the screen. So the label text would turn into a 1, then a 2, then a 3, etc. I threw this code into playground and the DispatchQueue seems to infinitely go up. Thanks.
var percentage = 0
func incrementLabel (amount: Int){
var count = 0
while count <= amount{
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: {
percentage += 1
count += 1
})
}
}
incrementLabel(amount: 10)
print(percentage)
推荐答案
这里有一个替代解决方案,您可以使用它来代替 DispatchQueue
:
Here is an alternative solution that you could use instead of DispatchQueue
:
var percentage = 0
var counter = 0
var timer: Timer?
func incrementLabel(amount: Int) {
counter = amount
timer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(self.updateDelay), userInfo: nil, repeats: true)
}
@objc func updateDelay() {
if (counter > 0) {
counter -= 1
percentage += 1
} else {
timer.invalidate()
timer = nil
}
}
incrementLabel(amount: 10)
print(percentage)
这在 Swift 中使用了 Timer
.
This uses Timer
in Swift.
这篇关于Swift:延迟增加标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!