Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Create a Circular Progress Bar in SwiftUI
Written by Team Kodeco

Providing users with clear, visual indications of progress for ongoing tasks enhances user experience. In SwiftUI, you can easily create a custom circular progress indicator. Below is an example of how to create a custom circular progress bar:

struct ContentView: View {
  @State private var progress: CGFloat = 0.2 // example progress value

  var body: some View {
    VStack {
      CircularProgressView(progress: progress)
        .frame(width: 200, height: 200) // adjust size as needed

      Slider(value: $progress, in: 0...1) // Slider to adjust progress for demonstration
        .padding()
    }
  }
}

struct CircularProgressView: View {
  let progress: CGFloat

  var body: some View {
    ZStack {
      // Background for the progress bar
      Circle()
        .stroke(lineWidth: 20)
        .opacity(0.1)
        .foregroundColor(.blue)

      // Foreground or the actual progress bar
      Circle()
        .trim(from: 0.0, to: min(progress, 1.0))
        .stroke(style: StrokeStyle(lineWidth: 20, lineCap: .round, lineJoin: .round))
        .foregroundColor(.blue)
        .rotationEffect(Angle(degrees: 270.0))
        .animation(.linear, value: progress)
    }
  }
}

Here’s what your preview should look like:

Create a custom circular progress indicator.
Create a custom circular progress indicator.

In this example, you create a CircularProgressView struct that represents our custom circular progress indicator. This custom view accepts a progress value between 0.0 and 1.0, where 0.0 means no progress and 1.0 means the task is complete.

The CircularProgressView creates two Circle views in a ZStack: one for the background of the progress bar, and one for the actual progress. The actual progress Circle uses the trim modifier to adjust the displayed arc based on the progress value. It also uses the rotationEffect modifier to rotate the progress circle to start from the top.

You also create a ContentView that contains the CircularProgressView. You provide an example progress value and create a Slider to manually adjust the progress value and see the progress bar update in real-time.

Note: This example is only for demonstration purposes. In a real-world app, the progress value would likely be updated by some other process such as a file download or data processing status.

By creating a custom circular progress indicator, you can provide a rich visual feedback to users and better match the design language of your app. Give this a try in your next app!

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.