85 - Customize the Style of Progress Indicators in SwiftUI

Creating a progress indicator in SwiftUI allows for ample customization to align with your app’s design. This entry will demonstrate how to modify the color and style of a progress bar.

You can adjust the color of a progress bar utilizing the accentColor modifier. This modifier alters the color for all control elements within a view, inclusive of progress bars. Consider the example below:

ProgressView(value: 0.5)
  .accentColor(.blue)

In the above code snippet, the accent color is set to blue, which subsequently changes the progress bar’s color to blue.

You can also modify the progress bar style with the progressViewStyle modifier. This modifier accepts a view that conforms to the ProgressViewStyle protocol.

Choosing a Progress View Style in SwiftUI

SwiftUI provides several built-in progress view styles:

Here’s an example of how to apply the CircularProgressViewStyle:

ProgressView(value: 0.5)
  .progressViewStyle(.circular)

In this snippet, the CircularProgressViewStyle is applied to the progress bar, which morphs it into a circular shape.

You can even define a custom progress view style by creating a struct that conforms to the ProgressViewStyle protocol. Here’s an example:

struct ContentView: View {
  var body: some View {
    CustomProgress()
  }
}

struct CustomProgress: View {
  @State private var progressValue = 0.5
  var body: some View {
    ProgressView(value: progressValue)
      .progressViewStyle(CustomProgressViewStyle())
      .onAppear {
        Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { timer in
          if progressValue < 1.0 {
            progressValue += 0.01
          } else {
            timer.invalidate()
          }
        }
      }
  }
}

struct CustomProgressViewStyle: ProgressViewStyle {
  func makeBody(configuration: Configuration) -> some View {
    VStack {
      ProgressView(value: configuration.fractionCompleted)
        .accentColor(configuration.fractionCompleted! < 1.0 ? .red : .blue)
      Text("\(Int((configuration.fractionCompleted ?? 0) * 100))%")
    }
  }
}

Your preview should look like this:

You can create a custom progress view style by conforming to ProgressViewStyle.

In this example, you’ve created a custom progress view style that displays the progress percentage and modifies the color based on whether the progress is currently animating.

By using these techniques, you’re equipped to create progress bars that seamlessly align with the style of your app, contributing to an engaging user experience.