Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SwiftUI ProgressView in List can only be displayed once

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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))

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading