Stepper in SwiftUI

DevTechie Inc
Jan 15, 2023

Stepper view in SwiftUI gives user ability to increment or decrement a discrete value. Stepper provides minus(-) and plus(+) button that can be tapped to select the exact number.

Stepper view works with any number type.

Let’s explore this with example. We will create a State property to bind Stepper’s value property and will use Stepper controls to increase or decrease the value.

struct DevTechieStepperExample: View {
    
    @State private var value = 26
    
    var body: some View {
        NavigationView {
            VStack {
                Text("Current value: \(value)")
                Stepper("What's your age?", value: $value)
            }
            .padding()
            .navigationTitle("DevTechie Login!")
        }
    }
}
We can limit Stepper’s range using in parameter.

Stepper("What's your age?", value: $value, in: 23...65)
When the value is reached. Stepper control gets disabled all by itself.

Just like Slider view, we can provide step parameter to Stepper as well.

Stepper("What's your age?", value: $value, in: 20...65, step: 5)
We can put custom logic for increment and decrement with another overload of Stepper.

Stepper("What's your age?", onIncrement: {
    value += 5
}, onDecrement: {
    value -= 5
})
Stepper formatting options are limited but we can change font color by using UIStepper’s appearance object. We will change plus and minus button images along with font size and color for the label.

struct DevTechieStepperExample: View {
    
    @State private var value = 0
    
    init() {
        UIStepper.appearance().setDecrementImage(UIImage(systemName: "hand.thumbsdown.circle.fill"), for: .normal)
        UIStepper.appearance().setIncrementImage(UIImage(systemName: "hand.thumbsup.circle.fill"), for: .normal)
    }
    
    var body: some View {
        NavigationView {
            VStack {
                Text("Current rating: \(value)")
                Stepper("Your rating?", onIncrement: {
                    value += 1
                }, onDecrement: {
                    value -= 1
                })
                .font(.largeTitle)
                .foregroundColor(.orange)
            }
            .padding()
            .navigationTitle("DevTechie Login!")
        }
    }
}
With that we have reached the end of this article. Thank you once again for reading. Don’t forget to follow 😍. Also subscribe our newsletter at https://www.devtechie.com