Swift:延迟

时间:2018-03-04 21:00:51

标签: swift while-loop uilabel

我的应用程序在到达代码的这一部分时会冻结。我试图以一半秒的延迟递增一个数字,然后将其打印到屏幕上。所以标签文本会变成1,然后是2,然后是3,等等。我把这个代码扔进游乐场,DispatchQueue似乎无限上升。感谢。

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 个答案:

答案 0 :(得分:0)

以下是您可以使用的替代解决方案,而不是Tier3Toolbox.EARTH_RADIUS = 6378137; /* Equitorial Radius instead of 6371000 */ Tier3Toolbox.toRad = function (num) { return num * Math.PI / 180; }; Tier3Toolbox.calculateDistance = function(lat1, lon1, lat2, lon2){ var dLat = this.toRad(lat2 - lat1); var dLon = this.toRad(lon2 - lon1); var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(this.toRad(lat1)) * Math.cos(this.toRad(lat2)) * Math.sin(dLon / 2) * Math.sin(dLon / 2); var distance = this.EARTH_RADIUS * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); return distance; }

DispatchQueue

这在Swift中使用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)