67 - Add a Stepper in SwiftUI

A stepper control allows users to increment or decrement a value by a predefined amount. Developers add this control in many situations, such as adjusting the quantity of an item in a cart, puchasing airline tickets for you and a couple friends and setting system wide preferences. It’s a common solution when you need to select a quantity or adjust a numeric value.

Here’s an example of how to add a stepper control to your SwiftUI application:

struct ContentView: View {
  @State private var quantity: Int = 1

  var body: some View {

    VStack(spacing: 10) {
      Text("How many packets of magic beans?")
      Stepper(value: $quantity, in: 1...10) {
        Text("\(quantity)")
      }
      .padding(.horizontal, 100)
    }
    .padding(30)
  }
}

Your preview should look like this:

SwiftUI's Stepper view takes a binding to a State variable.

Here’s how this code works:

By default, the stepper provides + and - buttons to increment or decrement the value by 1.

Try adding a stepper the next time you need to adjust values in your app!