Stepper iOS 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 label field using the UIStepper buttons.  This tutorial is made with Xcode 8.2.1 and built for iOS 10.2.

Open Xcode and create a new Single View Application.

For product name, use IOS10UIStepperTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and make sure only iPhone is selected in Devices.

Go to the Storyboard and drag a Label and a Stepper to the main View. Select the Label and in the Attributes inspector change the font in System Bold 25.0 and select the center alignment button. Give the Label a text Value of "0".

Select the Label and click the Pin Auto Layout button on the bottom-right of the Storyboard. Pin the button at the top edge and select "Items of New Constraints" at the Update Frames section. Select "Add 1 Constraint".

Select the button and click the Align Auto Layout button. Select the "Horizontally in Container" checkbox and select "Items of New Constraints" at the Update Frames section. Select "Add 1 Constraint".

Label-Align-Horizontal.png

Repeat the last step for the Stepper. Next, select the Stepper and Ctrl-drag or right-click-drag to the top Label. Select Vertical Spacing

Select the Assistant Editor and make sure the ViewController.swift file is visible. Ctrl-drag or right-click-drag from the Label to the ViewController class and create the following Outlet.

Ctrl-drag or right-click-drag from the Stepper to the ViewController class and create the following Outlet.

Ctrl-drag or right-click-drag from the Stepper to the ViewController class and create the following Action.

The Storyboard should look like this.

Go to the ViewController.swift file and change the viewDidLoad method to

override func viewDidLoad() {
  super.viewDidLoad()
  
  stepper.wraps = true 
  stepper.autorepeat = true
  stepper.maximumValue = 10
}

The stepper class has a few properties:

  • wraps: if set to true stepping beyond maximumvalue will return to minimumvalue
  • autorepeat: If  set to true, the user pressing and holding on the stepper repeatedly alters value.
  • maximumvalue: the maximum value of the stepper

Implement the stepperValueChanged method

@IBAction func stepperValueChanged(_ sender: UIStepper) {
    valueLabel.text = Int(sender.value).description
}

The description value of the Stepper is assigned to the text property of the Label. 

Build and Run the project, When the user clicks on the +/- symbols, the current value of the stepper will be assigned to the stepper label.

You can download the source code of the IOS10UIStepperTutorial at the ioscreator repository on github.