[英]How do I solve this: UILabel.text must be used from main thread only
So I am trying to update the UI in my application.所以我正在尝试更新我的应用程序中的 UI。 What happens is that the labels get updated but when they do not keep their own value but sometimes take the value of the other label.发生的情况是标签得到更新,但是当它们不保留自己的值但有时会采用其他 label 的值时。 Also, I get the message that the label should be used from main thread only, how do I solve this?另外,我收到消息说 label 只能从主线程使用,我该如何解决?
Here is my code:这是我的代码:
let queue = DispatchQueue(label: "update")
queue.async {
for s in self.fietshare.stands {
for b in s.bikes {
lbAvailable.text = "Available Bikes: " + String(s.id) + " " + String( s.bikes.count) // shows too big numbers
nrOfAvailable.text = String(b.distance) + "M"
annotationView.layoutIfNeeded()
print(s.id)
print("Nr of bikes")
print(s.bikes.count)
}
}
}
DispatchQueue.main.async {
self.view.backgroundColor = . black;
self.view.layoutIfNeeded()
}
if (Thread.current.isMainThread) {
print("Main thread")
}
Try this尝试这个
let queue = DispatchQueue(label: "update")
queue.async {
var available = ""
var nrOfAvailable = ""
for s in self.fietshare.stands{
for b in s.bikes {
available = available + "Available Bikes: " + String(s.id) + " " + String( s.bikes.count) // shows too big numbers
nrOfAvailable = String(b.distance) + "M"
print(s.id)
print("Nr of bikes")
print(s.bikes.count)
}
}
// UPDATE UI after all calculations have been done
DispatchQueue.main.async {
lbAvailable.text = available
nrOfAvailable.text = nrOfAvailable
annotationView.layoutIfNeeded()
self.view.backgroundColor = . black;
self.view.layoutIfNeeded()
}
}
Explanation:解释:
queue.async
你用queue.async
启动一个异步任务Explanation 2:解释二:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.