Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Create a Custom Progress View in SwiftUI
Written by Team Kodeco

Sometimes the built-in progress views don’t quite meet the exact requirements for your project. In such cases, SwiftUI provides a way to create custom progress views. In this cookbook entry, you’ll learn how to create a custom progress view in SwiftUI.

First, define a new view named CustomProgressView:

struct CustomProgressView: View {
  let progress: CGFloat

  var body: some View {
    GeometryReader { geometry in
      ZStack(alignment: .leading) {
        Rectangle()
          .frame(width: geometry.size.width, height: 10)
          .opacity(0.3)
          .foregroundColor(.gray)

        Rectangle()
          .frame(
            width: min(progress * geometry.size.width,
                       geometry.size.width),
            height: 10
          )
          .foregroundColor(.blue)
      }
    }
  }
}

In the above code, you have defined a CustomProgressView that takes a progress value as input. You then use GeometryReader to get the dimensions of the view, and a ZStack to stack two rectangles on top of each other. The first rectangle is the background and the second rectangle displays the progress made by the user. You use a .foregroundColor modifier to set the color of the progress indicator.

Next, create a sample view that uses this custom progress view.

struct ContentView: View {
  @State var progress: CGFloat = 0.5

  var body: some View {
    VStack {
      CustomProgressView(progress: progress)
        .frame(height: 10)
        .padding(.horizontal, 50)

      Button(action: {
        progress += 0.1
      }) {
        Text("Increase Progress")
      }
    }
  }
}

Your preview should look like this after you tap Increase Progress a couple times:

You can use a GeometryReader to create a custom progress view.
You can use a GeometryReader to create a custom progress view.

In the above code, you define ContentView, including the property @State var progress that you’ll use to update the progress indicator. You use the CustomProgressView that you defined earlier and bind the progress value to the @State variable. You also have a button that updates the progress value by 0.1 every time it is pressed.

By combining both, the user can now see and manipulate the progress within this custom progress view.

Congratulations! You now know how to create a custom progress view in SwiftUI.

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.