Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.

Advertisements