我想每秒钟为数组中的字符串更改一个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秒前不会改变,然后得到数组的最后一个字符串。
睡眠(1) 睡眠(1) 睡眠(1) 睡眠(1) 快走!
什么是预期的
3. 睡眠(1) 2 睡眠(1) 1 睡眠(1) 快走! 睡眠(1)
发布于 2018-07-05 09:12:44
为了避免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)
}
}发布于 2018-07-05 09:01:01
你能不要用计时器代替吗?
这是未经检验的。
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)
}
}https://stackoverflow.com/questions/51187053
复制相似问题