Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Add a Stepper in SwiftUI
Written by Team Kodeco

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.
SwiftUI's Stepper view takes a binding to a State variable.

Here’s how this code works:

  • @State private var quantity: Int = 1 : @State is a property wrapper that denotes a source of truth, which SwiftUI watches for changes. Any time quantity changes, SwiftUI invalidates the current view and triggers a new body computation, redrawing the UI with the updated value. The private keyword makes this state property only accessible within the current file. The initial value for quantity is set to 1.

  • VStack(spacing: 10) {...} : A VStack is a vertical stack that arranges views vertically. The spacing: 10 parameter sets a standard amount of spacing — 10 points — between each element inside the stack.

  • Text("How many packets of magic beans?") displays a static string of text in this handy beanstalk app.

  • Stepper(value: $quantity, in: 1...10) {...} creates a control for selecting a value within a range. Here, the stepper increments or decrements the quantity state variable. The range for the stepper value is set from 1 to 10.

  • Text("\(quantity)") : This is a child view within Stepper, which displays the current value of quantity.

  • .padding(.horizontal, 100) : This modifier adds horizontal padding of 100 points to the Stepper. This padding adds extra space around the Stepper, effectively forcing its label and control closer together.

  • .padding(30) : This modifier adds padding around the VStack. The amount of padding space is 30 points on all sides.

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!

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.