Programmatically creating UIStepper and UISegmentedControl Using Swift

UIStepper

UIStepper is the iOS UI component that provide the easiest way to implement the consecutive numeric value change. UIStepper has +/- signs for increment/decrement function. In this tutorial we will print the value in console depending on user ‘s interaction with UIStepper.

 

1
2
3
4
5
6
var customStepper = UIStepper (frame:CGRectMake(110, 250, 0, 0))
customStepper.wraps = true
customStepper.autorepeat = true
customStepper.maximumValue = 10
customStepper.addTarget(self, action: "stepperValueChanged:", forControlEvents: .ValueChanged)
self.view.addSubview(customStepper)

Now, Implementing the stepperValueChanged function for fetching the integer value :

1
2
3
4
func stepperValueChanged(sender:UIStepper!)
{
println("It Works, Value is -->\(Int(sender.value).description)")
}

Here is the how out Stepper will look like.

UIStepper-programmatically

 

 

UISegmentedControl

 

UISegmentedControl displays the list of the predefined options to user from which he/she can choose any one. Each segment can be used like radio button options, when selected other options are de-selected by default. In this tutorial we will learn about creating a UISegmentedControl programmatically having 3 options to choose and a method that get triggered and give us the index of the segment chosen when user presses one of them.

1
2
3
4
5
6
var customSegmentedControl = UISegmentedControl (items: ["one","two","three"])
customSegmentedControl.frame = CGRectMake(60, 250,200, 30)
customSegmentedControl.selectedSegmentIndex = 1
customSegmentedControl.tintColor = UIColor.redColor()
customSegmentedControl.addTarget(self, action: "segmentedValueChanged:", forControlEvents: .ValueChanged)
self.view.addSubview(customSegmentedControl)

and “segmentedValueChanged()” will be triggered, and it will print logs on console.

1
2
3
4
func segmentedValueChanged(sender:UISegmentedControl!)
{
println("It Works, Value is -->\(sender.selectedSegmentIndex)")
}

Here is how our custom segmented control will look like:

UISegmentedControl-programmatically

  • Van

    WORK with copying the code and paste
    Thank

    • AppTuitions

      Copy & Paste always works… 😉

  • DFB

    Excellent tutorial
    Many thanks
    Be cool you would add others!