Advertisements
I am working on a feature which takes a few seconds. So I want to display a ProgressView
when my logic is in progress.
Not sure if this is a bug in SwiftUI, but in the following code, when I click the button the second time, the progress view does not show up anymore (The first click is fine tho)
struct ContentView: View {
@State var inProgress = false
var body: some View {
List {
if inProgress {
HStack {
Text("Waiting...")
ProgressView()
}
} else {
Button("Click Me") {
inProgress = true
Task {
try? await Task.sleep(nanoseconds: UInt64(2 * 1_000_000_000))
inProgress = false
}
}
}
}
}
}
Note that this problem only happens under a List
. If I change it to a VStack
, then the ProgressView
is displayed every time I click the button.
>Solution :
To show the ProgressView
every time you click, add a new .id()
to the HStack
(or the ProgressView), so that it gets re-drawn:
HStack {
Text("Waiting...")
ProgressView()
}.id(UUID()) // <--- here
Note, you can also use Task.sleep(for: .seconds(2))