Swift: Incrementing label with delay

久未见 提交于 2019-12-11 16:54:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!