How to programmatically add a UISegmentedControl to a container view?


To add a UISegmentControl in iOS with swift we’ll have to first create a segment control and it’s controller function, i.e. it’s action. Let’s see those steps.

Let’s create a function to add a segmented control.

func addControl() {
   let segmentItems = ["First", "Second"]
   let control = UISegmentedControl(items: segmentItems)
   control.frame = CGRect(x: 10, y: 250, width: (self.view.frame.width - 20), height: 50)
   control.addTarget(self, action: #selector(segmentControl(_:)), for: .valueChanged)
   control.selectedSegmentIndex = 1
   view.addSubview(control)
}

This function may be called in our view controller to add the segmented control, let’s add action for this control.

@objc func segmentControl(_ segmentedControl: UISegmentedControl) {
   switch (segmentedControl.selectedSegmentIndex) {
      case 0:
         // First segment tapped
      break
      case 1:
         // Second segment tapped
      break
      default:
      break
   }
}

When we run the same code on an iOS simulator below Is the output that’s produced.

Updated on: 30-Jul-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements