我想每秒为数组内的String更改UILabel.text。
为此,我编写了以下代码并将其放在viewDidAppear中。
let countdown = ["3", "2", "1", "GO !"]
for i in 0..<countdown.count {
self.countdownStatus.text = countdown[i]
sleep(1)
}
发生了什么
UILabel.text在4秒前没有更改,然后获取数组的最后一个字符串。
sleep(1)
sleep(1)
sleep(1)
sleep(1)
GO!
期待什么
3
sleep(1)
2
sleep(1)
1
sleep(1)
GO!
sleep(1)
答案 0 :(得分:2)
为避免UI阻塞,请将整个例程分派到全局que,然后将UI部分分派到主队列。
DispatchQueue.global().async {
let countdown = ["3", "2", "1", "GO !"]
for i in 0..<countdown.count {
DispatchQueue.main.async {
self.countdownStatus.text = countdown[i]
}
sleep(1)
}
}
答案 1 :(得分:0)
您可以不尝试使用计时器吗?
这未经测试。
let myTimer : Timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.performCountdown), userInfo: nil, repeats: false)
let countdown = ["3", "2", "1", "GO !"]
var i = 0
func performCountdown() {
while i < 4{
print(countdown[i])
i = i+1
}
您也可以使用后台线程,该线程已经过测试并且可以正常工作
import Foundation
import UIKit
let countdown = ["3", "2", "1", "GO !"]
DispatchQueue.global(qos: .background).async {
for i in 0..<countdown.count {
print(countdown[i])
sleep(1)
}
}