SwiftUI Stepper Tutorial

The UIStepper control  provides a simple way to change a numeral value. It consists of +/- symbols that increment/decrement an internal value. In this tutorial we will change the value of a Text view using the UIStepper buttons. SwiftUI requires Xcode 11 and MacOS Catalina, for which the Betas can be downloaded at the Apple developer portal.

Open Xcode and either click Create a new Xcode project in Xcode’s startup window, or choose File > New > Project. In the template selector, select iOS as the platform, select the Single View App template, and then click Next. Enter SwiftUITutorial as the Product Name, select the Use SwiftUI checkbox, and click Next. Choose a location to save the project on your Mac.

In the canvas, click Resume to display the preview. If the canvas isn’t visible, select Editor > Editor and Canvas to show it.

In the Project navigator, click to select ContentView.swift. Change the code inside the ContentView struct to

struct ContentView: View {
    // 1.
    @State var numberOfItems: Int = 0
    
    var body: some View {
        // 2.
        Stepper(value: $numberOfItems, in: 0...10, label: { Text("Number of items:  \(numberOfItems)")}).padding()
    }
}
  1. A State property is declared. The initial value of the stepper is 0.

  2. A Stepper is displayed with a value of 0 to 10. The current stepper value will be displayed in a text view.

Go to the preview pane and go to live mode. Change the stepper value and the text will change with the current value.

The source code of the SwiftUIStepperTutorial can be downloaded at the ioscreator repository on Github.