Indicate Indeterminate Progress with SwiftUI
Written by Team Kodeco
Indicating progress in an app is crucial for keeping users informed about the status of their actions. Sometimes, however, it’s not feasible to know how long a given task will take to complete. In such cases, you can use an indeterminate progress view to let users know that their action is still ongoing, even if you don’t know how long it will take to complete.
To create an indeterminate progress view in SwiftUI, you can use ProgressView
with an unbounded progress constant.
struct ContentView: View {
var body: some View {
IndeterminateProgressView()
}
}
struct IndeterminateProgressView: View {
@State private var isLoading = true
var body: some View {
VStack {
ProgressView("Loading…")
.progressViewStyle(.circular)
.scaleEffect(2.0, anchor: .center) // Optional: make it bigger
}
.onAppear {
startAnimating()
}
}
func startAnimating() {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
withAnimation(Animation.linear(duration: 1.5).repeatForever()) {
isLoading = true
}
}
}
}
Your preview should look like this:
In the code example, you first declare a @State
variable called isLoading
. Inside the body
, you create a VStack
container and use ProgressView
to display a spinning activity indicator with the message “Loading…”. You also add the .circular
parameter to the progressViewStyle
modifier to apply the CircularProgressViewStyle
to the ProgressView
.
To make the progress indicator bigger, you add the scaleEffect
modifier.
To start and stop the animation, you use the startAnimating
function. This function simply sets isLoading
to true after a 0.5-second delay, and then begins a repeatForever
animation that changes the value of isLoading
.
Now you know how to implement an indeterminate progress view in SwiftUI. If you need to indicate progress that you can measure, check out the previous entry on creating a determinate progress view.