top of page
Writer's pictureHui Wang

27. SwiftUI: Introducing Stepper

Today I will show you how to use Stepper.

Stepper has an "+" button, a "-" button, and a value label, perfect for fine-tuning the value in a small range.


Knowledge points:

  • First, add a property of type Double and set its initial value to 0.

  • This property has a @State property wrapper, which means that the property will be data-bound to the Stepper.

@State var progress: Double = 0


Next:

  • Add a Stepper, then set the onIncrement, onDecrement events, and the label.

Stepper {
    // onIncrement
} onDecrement: {
    // onDecrement
} label: {
    // label
}

Next:

  • Set the onIncrement event of Stepper. When the user clicks the "+" button, increase the progress value.

  • Set the onDecrement event of Stepper. When the user clicks the "-" button, decrease the progress value.

  • Set the Stepper label to display the value of the progress property.

  • Set the padding of VStack to keep a certain distance between UI elements and the left and right sides of the screen.

VStack {
    Stepper {
        progress += 1
    } onDecrement: {
        progress -= 1
    } label: {
        Text("Progress: \(Int(progress))")
    }
}
.padding()


Source Code:

struct ContentView: View {
    
    @State var progress: Double = 0
    
    var body: some View {
        VStack {
            Stepper {
                progress += 1
            } onDecrement: {
                progress -= 1
            } label: {
                Text("Progress: \(Int(progress))")
            }
        }
        .padding()
    }
}

 

Follow me on:

Comments


bottom of page