在功能中更新标签

问题描述 投票:-1回答:1

如果您有一个像下面这样的简单例程,那么如何在循环中更新标签?当我运行它时,它只会在其功能完成时才在末尾更新。

for loop in 1...10 {
    doCalculation()

    resultLabel.text = String(result)

    sleep(1)
}

function doCalculation() {

    ... perform calculation updating variable result ...

}

我也尝试过,但这不能解决。

for loop in 1...10 {
    doCalculation()

    DispatchQueue.main.async {
      self.resultLabel.text = String(self.result)
    }

    sleep(1)
}
swift
1个回答
0
投票

您可以尝试Timer

Swift的Timer类是一种安排工作安排的灵活方式,未来,一次或多次。

let timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
    print("Timer fired!")
}

可以在herehere中找到更详细的说明。

© www.soinside.com 2019 - 2024. All rights reserved.