How to show progress on a task using ProgressView
About 2 min
How to show progress on a task using ProgressView 관련
SwiftUI by Example
Back to Home
How to show progress on a task using ProgressView | SwiftUI by Example
How to show progress on a task using ProgressView
Updated for Xcode 15
SwiftUI's ProgressView
can be bound to a Double
to show a horizontal progress bar. For example, this creates a progress bar with the title “Downloading”, that will read downloadAmount
to determine how full the progress bar should be:
struct ContentView: View {
@State private var downloadAmount = 0.0
var body: some View {
VStack {
ProgressView("Downloading…", value: downloadAmount, total: 100)
}
}
}
![The text “Downloading” over an almost empty progress bar.](https://hackingwithswift.com/img/books/quick-start/swiftui/how-to-show-progress-on-a-task-using-progressview-1~dark.png)
In practice, you'll need some way to actually change that value, such as a timer, a network request, or other user interface. For example, this will fill the progress bar up over a few seconds:
struct ContentView: View {
@State private var downloadAmount = 0.0
let timer = Timer.publish(every: 0.1, on: .main, in: .common).autoconnect()
var body: some View {
ProgressView("Downloading…", value: downloadAmount, total: 100)
.onReceive(timer) { _ in
if downloadAmount < 100 {
downloadAmount += 2
}
}
}
}
Note
Xcode will get angry if you set your progress value higher than the progress total – make sure you cap it as you can see above.
Similar solutions…
How to show indeterminate progress using ProgressView | SwiftUI by Example
How to show indeterminate progress using ProgressView
Customizing ProgressView with ProgressViewStyle | SwiftUI by Example
Customizing ProgressView with ProgressViewStyle
How to run an asynchronous task when a view is shown | SwiftUI by Example
How to run an asynchronous task when a view is shown
How to show an action sheet | SwiftUI by Example
How to show an action sheet
How to hide and show the sidebar programmatically | SwiftUI by Example
How to hide and show the sidebar programmatically