In this tutorial i’ll show you how to create (Interface builder and programmatically) and how to use UIStepper in a iOS application.
Create a new Xcode Project, new Single View Application
In Product Name insert UIStepperTutorial and click Next
Interface Builder
From objects library drag: UIStepper and two UILabel.
In the first label we will show the UIStepper value created by Interface Builder, in the second label, one created programmatically, then write 0 in the labels
Now create an IBOutlet for the labels and for the stepper and an UIAction for the stepper.
You can do this holding down ctrl key and drag to editor view
Now we set the stepper value when it changes
1 2 3 4 5 |
@IBAction func ibStepperSetValue(sender: UIStepper) { let stepperValue = Int(sender.value) ibStepperValue.text = String(stepperValue) } |
Programmatically
To create an UIStepper, we declare a progStepper variable in our ViewController
1 |
var progStepper: UIStepper! |
Then we add a function that will be called in the viewDidLoad method
1 2 3 4 5 6 7 8 9 10 |
func createProgStepper() { progStepper = UIStepper() progStepper.frame = CGRectMake(140, 270, 0, 0) progStepper.minimumValue = 0 progStepper.maximumValue = 100 progStepper.autorepeat = true progStepper.continuous = true progStepper.tintColor = UIColor.redColor() self.view.addSubview(progStepper) } |
- Initialize an UIStepper object
- Set the position (x: 140, y: 270) and the stepper size default (0,0)
- Set the minimum and maximum value
- Set autorepeat to true (If true, the user pressing and holding on the stepper repeatedly alters value)
- Set continuous to true (If true, value change events are sent immediately when the value changes during user interaction. If false, a value change event is sent when user interaction ends)
- Set the color to red
- Add the stepper as a subview of the view
Now we create a function that will be called when the stepper is clicked.
The code of this function is the same that we wrote for the stepper created with Interface Builder, will set the stepper value when it changes
1 2 3 4 |
func progStepperSetValue(sender: UIStepper!) { let stepperValue = Int(sender.value) progStepperValue.text = String(stepperValue) } |
This is the code for the viewDidLoad method
1 2 3 4 5 6 7 8 9 |
override func viewDidLoad() { super.viewDidLoad() // Create the stepper createProgStepper() // Set the stepper value when it changes progStepper.addTarget(self, action: "progStepperSetValue:", forControlEvents: .ValueChanged) } |
If you want know more about UIStepper you can refer to the official documentation.
Download the complete code here.