Creating UISegmentedControl via code

suggest change
  1. Create new instance of UISegmentedControl filled with 3 items (segments):
let mySegmentedControl = UISegmentedControl (items: ["One", "Two", "Three"])
  1. Setup frame;
mySegmentedControl.frame = CGRect(x: 0.0, y: 0.0, width: 300, height: 50)
  1. Make default selection (not that segments are indexed by 0):
mySegmentedControl.selectedSegmentIndex = 0
  1. Configure target:
mySegmentedControl.addTarget(self, action: #selector(segmentedValueChanged(_:)), for: .valueChanged)

5 Handle value changed:

func segmentedValueChanged(_ sender:UISegmentedControl!) {
    print("Selected Segment Index is : \(sender.selectedSegmentIndex)")
  1. Add UISegmentedControl to views hierarchy

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents