Implement a Determinate Progress Bar in SwiftUI
Written by Team Kodeco
When you need to display progress that has a clear start and end point, a determinate progress bar is a great option. In SwiftUI, you can create a determinate progress bar using ProgressView
and binding the current progress to a value that tracks progress.
Here’s an example:
struct ContentView: View {
@State private var downloadProgress = 0.0
@State private var timer: Timer? = nil
var body: some View {
VStack {
ProgressView("Downloading...", value: downloadProgress, total: 100)
.progressViewStyle(.linear)
Button("Start Download") {
simulateDownload()
}
}
}
func simulateDownload() {
timer?.invalidate() // Cancel the previous timer if any
downloadProgress = 0.0 // Reset the progress
timer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true) { timer in
if downloadProgress < 100 {
downloadProgress += 1.0
} else {
timer.invalidate()
}
}
}
}
Tap Start Download and your preview should look like this:
In this example, you first create a state variable to track the progress of the download. You then use this variable to bind the value of the progress bar by passing it as the value
parameter to the ProgressView
, along with the total progress as the total
parameter. You also set the style of the progress bar to a linear style, though there are other styles available, including circular.
In the view, you display the progress bar along with a button to start the download. When the button is pressed, you simulate the progress of the download by starting a Timer
that fires every 0.5 seconds. On each tick, it increments downloadProgress
by 1, simulating a download progress, until it reaches 100.0.
And that’s it! With just a few lines of code, you now have a basic determinate progress bar in your SwiftUI app.