Create UIStepper Programmatically

The below Swift code example demonstrates how to create a UIStepper programmatically.

If you are interested in video lessons on how to write Unit tests and UI tests to test your Swift mobile app, check out this page: Unit Testing Swift Mobile App

If we break it down into smaller parts the code example below also demonstrates:

  • How to add UIStepper as a Subview,
  • Add custom function which gets triggered when UIStepper value is changed,
  • Position UIStepper in the center of UIView,
  • Make UIStepper value continuously increment when user taps and holds UIStepper button,
  • Make UIStepper resume from the beginning when the maximum value is reached.
import UIKit
class ViewController: UIViewController {
    override func viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let myUIStepper = UIStepper (frame:CGRect(x: 10, y: 150, width: 0, height: 0))
        // Resume UIStepper value from the beginning
        myUIStepper.wraps = true
        // Position UIStepper in the center of the view =
        // If tap and hold the button, UIStepper value will continuously increment
        myUIStepper.autorepeat = true
        // Set UIStepper max value to 10
        myUIStepper.maximumValue = 10
        // Add a function handler to be called when UIStepper value changes
        myUIStepper.addTarget(self, action: #selector(self.stepperValueChanged(_:)), for: .valueChanged)
    @objc func stepperValueChanged(_ sender:UIStepper!)
        print("UIStepper is now \(Int(sender.value))")
    override func didReceiveMemoryWarning() {
        // Dispose of any resources that can be recreated.

For more Swift code examples and tutorials, please check the Swift Code Examples page on this website.

Leave a Reply

Your email address will not be published.