Using the Stepper View in SwiftUI
The Stepper
is a control view that allows the user to perform increment or decrement actions. It is used to let the user increase or decrease a value within a predefined range. Let's look at an example:
import SwiftUI
struct ContentView: View {
// 1
@State var quantity = 0
var body: some View {
// 2
Stepper("Quantity: \(quantity)", value: $quantity, in: 0...50)
.padding(.horizontal)
}
}
- We create a state variable of type
Int
to store theStepper
value.
2. We create the Stepper
, specifying a title, its Binding
value, and the range it will operate in. In our case, we want it to go from 0 to 50.
With the Stepper
, users can easily adjust numeric values within a specific range. This view is especially useful for selecting quantities, configuration adjustments, and other value adjustment actions.
Taking Control of the Stepper
If we want more control over the value changes when using the Stepper
, we can use one of its completionHandler
s, such as onIncrement
and onDecrement
. Let's see how:
Stepper("Quantity: \(quantity)") {
// 1
quantity += 2
} onDecrement: {
// 2
quantity -= 2
}
.padding(.horizontal)
- We use the
completionHandler
onIncrement
, so each time it executes, we add 2 to ourquantity
variable. - Now we use
onDecrement
to subtract 2 from ourquantity
variable.
In addition to these two completionHandler
s, we also have onEditingChanged
, which runs each time editing starts and ends. For example, if the button is held down, onEditingChanged
will execute at the start and end of the button press gesture. Let's see how it works:
Stepper("Quantity: \(quantity)", value: $quantity, in: 0...100) { changed in
// 1
print(changed)
}
- When the gesture starts, the
changed
variable will betrue
, and when the gesture ends, it will befalse
.
Using Stepper
in SwiftUI is a straightforward way to provide users with precise control over numeric values. By leveraging the completionHandler
s, developers can create more interactive and responsive interfaces tailored to the needs of their applications.