So I am trying to update the UI in my application. 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. Also, I get the message that the label should be used from main thread only, how do I solve this?
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
Explanation 2:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With