SwiftUI_visionOS_Note

Stepper

Feb 1, 2024
2 min read|
  • This component allows users to increment or decrement a value by clicking + and - signs on stepper.
Stepper | Apple Developer Documentation
Stepper | Apple Developer Documentation

A control that performs increment and decrement actions.

  • We can use a stepper to:
    1. Change a value up or down by 1
    1. Operate strictly over a prescribed range.
    1. Step by specific amounts over a stepper’s range of possible values

1. Create Stepper

Stepper("Stepper", value: Binding<Strideable>)
swift

what is Strideable?

A type representing continuous, one-dimensional values that can be offset and measured.

You can use a type that conforms to the Strideable protocol with the stride(from:to:by:) and stride(from:through:by:)functions. For example, you can use stride(from:to:by:) to iterate over an interval of floating-point values:

  1. Create an integer variable with value 10, and bind it into value: with $ sign
@State var stepperValue: Int = 10
    
    var body: some View {
        Stepper("Stepper", value: $stepperValue)
    }
swift

  1. add a variable inside the text, using \(variable)
Stepper("Stepper: \(stepperValue)", value $stepperValue).padding(20)
swift

2. Create new stepper

We will create a rectangle that changes the size by clicking the stepper

  • Choose a stepper with onIncrement and onDecrement
Stepper("Stepper 2") {
...
} onDecrement: {
...
}
swift

  • Create integer 0 variable
@State var add: Int = 0
swift

  • Add add into a rounded rectangle width
RoundedRectangle(cornerRadius: 25.0)
	.frame(width: 100 + CGFloat(add), height: 100)
swift

  • add variable into the increment and decrement
Stepper("Stepper 2") {
add += 10
} onDecrement: {
add -= 10
}
swift

  • Add easeInOut animation to Stepper by creating outside function
func incrementWidth(amount: CGFloat){
	withAnimation(.easeInOut){
			add += Int(amount)
		}
}
swift
Stepper("Stepper 2") {
                incrementWidth(amount: 10)
            } onDecrement: {
                incrementWidth(amount: -10)
            }
swift

Stepper enables users to increase or decrease a value by clicking the + and - signs.

The view element can be edited or modified smoothly using withAnimation.

  • I have been busy with rescheduling aspects of my married life.

I'm uncertain about the product number as Fynn hasn't requested a spec sheet for that product yet.

Subscribe to our newsletter

Get the latest news and updates from our team