Using the Stepper View in SwiftUI

AsyncLearn
2 min readJul 22, 2024

--

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)
}
}
  1. We create a state variable of type Int to store the Stepper 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.

Example of using the Stepper view in SwiftUI

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 completionHandlers, such as onIncrement and onDecrement. Let's see how:

Stepper("Quantity: \(quantity)") {
// 1
quantity += 2
} onDecrement: {
// 2
quantity -= 2
}
.padding(.horizontal)
  1. We use the completionHandler onIncrement, so each time it executes, we add 2 to our quantity variable.
  2. Now we use onDecrement to subtract 2 from our quantity variable.

In addition to these two completionHandlers, 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)
}
  1. When the gesture starts, the changed variable will be true, and when the gesture ends, it will be false.

Using Stepper in SwiftUI is a straightforward way to provide users with precise control over numeric values. By leveraging the completionHandlers, developers can create more interactive and responsive interfaces tailored to the needs of their applications.

--

--

AsyncLearn
AsyncLearn

Written by AsyncLearn

Stay up-to-date in the world of mobile applications with our specialised blog.

No responses yet