A Stepper in SwiftUI is a user interface control that performs increment and decrement operations of a value. The user can decrease on increase the value by tapping its minus or plus element.
In this tutorial, you are going to learn how to create a stepper in SwiftUI. To check out the value changes, we have to read the value from the stepper. For this reason, we have to bind the stepper value to a state variable or we need to instantiate it with custom closures.
Let’s see our first example of creating a stepper, read the live changes of stepper value and show it in Text view:
@State var stepperValue = 5
var body: some View {
Stepper("Stepper value", value: $stepperValue, in: 0...36)
Text("Value of stepper is \(stepperValue)")
}
In the above example, we have declared a state variable and assigned an integer value of 5 to it. 5 is going to be the default value for our stepper.
After that, we created a stepper using SwiftUI Stepper control and use the value of our state variable stepperValue
. We have provided the range of our stepper from 0 to 36 so that the user can increase the value up to 36 and decrease the value up to 0.
Below is what it looks like:
Stepper without range:
Note that, providing a range to a stepper is optional. That means, there will be no error shown from Xcode if we don’t provide any range:
Stepper("Stepper value", value: $stepperValue)
In the above example, you see that we are showing the stepper value through a text view. But it is possible to show up the stepper value through the stepper control as you can see in the example below:
@State var stepperValue = 5
var body: some View {
Stepper("Stepper value \(stepperValue)", value: $stepperValue, in: 0...36)
}
Below is the screenshot of the user interface for the above code:
By default, the step value of a stepper control is 1. That means, tapping the decrement or increment icon decreases or increases the value by 1. However, you can set the step value of a stepper. Below is how it can be done:
Stepper("Stepper value", value: $stepperValue, in: 0...76, step: 4)
Below is another example without the range:
Stepper("Stepper value", value: $stepperValue, step: 4)
As you can see, we have provided a step parameter with the step value 4. Now tapping the increment and decrement icons will change the value by 4.