Creating Stepper Using A Binding Value
Let’s start by creating a basic stepper to change date using a binding value:
Code:
struct ContentView: View {
@State private var hours = 1
var body: some View {
VStack {
Stepper("Number of hours: \(hours)", value: $hours)
}.padding()
}
}
Output:
To create an upper limit on the range: as say a business might want to limit the number of hours of offered service, we can create restrictions to the upper and lower limits
Code:
struct ContentView: View {
@State private var hours = 1
var body: some View {
VStack {
Stepper("Stepper value: \(hours)", value: $hours, in: 0...6)}
}}
Output:
As you can see, upon reaching the value of 6, the + sign is greyed out and we cannot exceed the 6 value.
To decide the amount to increment by:
Code:
struct ContentView: View {
@State private var hours = 1
var body: some View {
VStack {
Stepper("Number of hours of service: \(hours)", value: $hours, in: 1...9, step: 2)}
}}
Output:
Initial
Output:
After first increment (automatically increments by 2)
For decimal values:
Code:
struct ContentView: View {
@State private var amount = 1.0
var body: some View {
VStack {
Stepper("Amount: \(amount, specifier:"%.2f")", value: $amount, in: 1...5, step: 0.5)}
}}
Output:
Initial
Output:
After first increment