SwiftUI Stepper Code and Examples

SwiftUI Stepper lets users adjust values via plus/minus buttons. Learn to implement, customize, set ranges, and handle value changes.
Written by

Joash Tubaga

Updated on

Aug 06 2024

Table of contents

    Overview

    The SwiftUI Stepper is a user interface component that allows users to increment or decrement a value by tapping a plus or minus button. This article explores how to implement and customize a Stepper in SwiftUI, including setting its range and handling its value changes programmatically.

    Code Snippet

    Swift
    import SwiftUI
    
    struct StepperView: View {
        @State private var quantity = 1
    
        var body: some View {
            VStack(spacing: 20) {
                Text("Select Quantity")
                    .font(.title)
                Stepper("Quantity: \(quantity)", value: $quantity, in: 1...10)
                Text("You have selected \(quantity) items.")
            }
            .padding()
        }
    }

    Code Explanation

    • @State private var quantity = 1: This line initializes a state variable quantity that will store the current value shown by the Stepper.
    • Stepper("Quantity: \(quantity)", value: $quantity, in: 1...10): The Stepper is created with a text label that displays the current quantity. It binds to the quantity variable and allows values from 1 to 10.
    • The view displays the current value of quantity alongside a label, updating in real-time as the Stepper is used.

    This code example demonstrates how to use a Stepper to adjust the quantity of items, with the user being able to increase or decrease the number between 1 and 10. It showcases the binding of SwiftUI state variables to user interface elements for interactive and dynamic UI updates.

    The SwiftUI Stepper is an essential component for creating interfaces where users need to adjust values within a defined range. It is versatile, easy to implement, and can be customized to fit the needs of various applications, making it a valuable tool for developers building user-centric apps.



    Get started for free

    Join over 2,000+ students actively learning with CodeWithChris