Stepper in SwiftUI

Rishabh Jain
2 min readMay 28, 2020

Introduction

Pre-requisite for SwiftUI development :-

  1. Xcode 11
  2. MacOS Catalina 10.15.2

Getting Started

A control used to perform semantic increment and decrement actions. The UIStepper control provides a simple way to change a numeral value. It consists of +/- symbols that increment/decrement an internal value.

  1. Create a stepper
  2. Restrict stepper values to a range
  3. Using onIncrement and onDecrement

Application Entry Point

Creating a New Project for Playing with SwiftUI. First, fire up Xcode and create a new Project. I created a project named DemoStepper.

Once you save the project, Xcode should load the ContentView.swift file and display a design/preview canvas.

By default, Xcode generates some SwiftUI code for ContentView.swift. However, the preview canvas doesn’t render the app preview. You have to click the Resume button in order to see the preview.

Create a stepper

Define a State variable holding the stepper’s value and then pass its binding when initializing the stepper:

Stepper("Updated value: \(stepperValue)", value: $stepperValue)

Restrict stepper values to a range

Here we are allow values between 0 to10.

Stepper("Stepper value: \(stepperValue)", value: $stepperValue, in: 0...10)

Using onIncrement and onDecrement

In order to perform custom action upon each increment and decrement, it is possible to pass custom closures to handle each case.

Here the value will be increment in multiple of 5 if you click on + and on click of - the value will be decrement in multiple of 5

Stepper(onIncrement: {
self.stepperValue += 5
}, onDecrement: {
self.stepperValue -= 5
}, label: { Text("Updated value: \(stepperValue)") })

Conclusion

I hope you enjoyed reading this. In this tutorial, we got an introduction about the Stepper control of SwiftUI.

Please find the Github link.
Github:- https://github.com/imrishuj/SU-Stepper

Thanks for reading and good luck with your next SwiftUI Tutorial!

--

--