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:
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 timequantity
changes, SwiftUI invalidates the current view and triggers a new body computation, redrawing the UI with the updated value. Theprivate
keyword makes this state property only accessible within the current file. The initial value forquantity
is set to1
. -
VStack(spacing: 10) {...}
: AVStack
is a vertical stack that arranges views vertically. Thespacing: 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 thequantity
state variable. The range for the stepper value is set from 1 to 10. -
Text("\(quantity)")
: This is a child view withinStepper
, which displays the current value ofquantity
. -
.padding(.horizontal, 100)
: This modifier adds horizontal padding of 100 points to theStepper
. This padding adds extra space around theStepper
, effectively forcing its label and control closer together. -
.padding(30)
: This modifier adds padding around theVStack
. 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!