Stepper is a SwiftUI control that allows users to increment or decrement a numeric value by tapping buttons or swiping on the screen. It can be used to enter values such as amount, age, or any other numeric value required by the application.
Stepper is made up of two buttons and a label. The label shows the current value of the stepper and the buttons allow the user to increment or decrement the value. By default, Stepper increments or decrements the value by 1, but this can be customized to any value required by the application.
To implement a stepper in SwiftUI, we first need a state variable to store the current value of the stepper. The first thing we do is declare the state variable as follows:
@State private var maxPriceLevel = 5
To create a stepper, a Stepper component is created:
Stepper(onIncrement: {
self.maxPriceLevel += 1
if self.maxPriceLevel > 5 {
self.maxPriceLevel = 5
}
}, onDecrement: {
self.maxPriceLevel -= 1
if self.maxPriceLevel < 1 {
self.maxPriceLevel = 1
}
}) {
Text("Show \(String(repeating: "$", count: maxPriceLevel)) or below")
}
For the onIncrement parameter, we specify the action to be performed when the + button is clicked. In the code, we simply increase maxPriceLevel by 1. In contrast, the code specified in the onDecrement parameter will be executed when the button is clicked.
Since the price level is in the range of 1 to 5, we perform a check to make sure that the value of maxPriceLevel is between 1 and 5. In the closure, we display the text description of the filter preference. The maximum price level is indicated by dollar signs
In XCode it would give the following result:
As with most views in SwiftUI, we can use multiple initializers. In this case, we are going to use another initializer as follows:
First, we create the state variable:
@State private var yourAge = 0
and we use the following Stepper initializer:
Stepper("Enter your age", value: $maxPriceLevel, in: 0...100)
Text("Your age is \(yourAge)")
So in XCode the result is as follows: