I like to update a text on the screen to inform the user about the progress. I'm using Text in SwiftUI. Whenever I change this message, it should be updated, even if the process is still running. E.g:
@State private var message = "-"
var body: some View {
VStack {
Button("Run") {
print("Tapped!")
for i in 0 ... 100 {
self.message = "\(i)"
for _ in 1...1000 {
print(".") // some time consuming stuff
}
}
}
Text(message)
.frame(width: 100)
.padding()
}
.padding(40)
}
When I change the message, it should be updating the screen. Unfortunately it only updates the text, when the loops are finished, so it shows 100. It should show 1, 2, ... 100.
Do I need special tricky queues like in the classic development using "DispatchQueue.main.async" etc or is there an easier way in SwiftUI?
I prefer DispatchQueue
, so some alternate
Button("Run") {
print("Tapped!")
DispatchQueue.global(qos: .background).async {
for i in 0 ... 100 {
DispatchQueue.main.asych {
self.message = "\(i)"
}
for _ in 1...1000 {
print(".") // some time consuming stuff
}
}
}
}