问题
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)
回答1:
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)
This uses Timer
in Swift.
来源:https://stackoverflow.com/questions/49100426/swift-incrementing-label-with-delay