Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Add a Progress View in SwiftUI
Written by Team Kodeco

A progress view is used to visualize the completion of a task or process. SwiftUI offers an easy-to-use way to add this view to your app.

Imagine you are building an app that downloads a file from the internet. You want to add a progress view to show the user how much of the download has been completed. Here’s how you can do it in SwiftUI:

struct ContentView: View {
  @State var progressValue = 0.0  // initial value of progress view
  
  var body: some View {
    VStack {
      ProgressView(value: progressValue) // progress view
        .padding()
      
      Button("Start Download") {
        // simulate the download progress
        for i in 1...100 {
          DispatchQueue.main.asyncAfter(deadline: .now() + Double(i) / 10.0) {
            progressValue = Double(i) / 100.0
          }
        }
      }
    }
  }
}

Your preview should look like this:

Use SwiftUI's ProgressView to display a progress bar.
Use SwiftUI's ProgressView to display a progress bar.

In this code, you first create a new variable progressValue with an initial value of 0.0. You then add a VStack which contains the ProgressView and a button to start the download. The ProgressView is created using the ProgressView(value:) constructor, which takes the value of the progress as an argument. In this case, we pass in progressValue.

DispatchQueue.main.asyncAfter(deadline: .now() + Double(i) / 10.0) introduces a delay before updating progressValue. The delay is i / 10.0 seconds, so the total time to fill the progress view will be about 10 seconds. You can adjust this value to make the progress view change more quickly or slowly.

Please note that SwiftUI’s ProgressView and the UI updates may not accurately represent the delay introduced in your loop because SwiftUI optimizes UI updates. If you want more precise control over the animation, you should consider using an animation or a timer.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.