Để thêm UISegmentedControl (điều khiển phân đoạn) vào view bằng code Swift, cần tạo segment control, cấu hình items, frame, action, và addSubview.
Tạo hàm thêm Segmented Control
func addSegmentedControl() {
let items = ["First", "Second", "Third"]
let segmentedControl = UISegmentedControl(items: items)
// Frame: cách trái 10, top 250, rộng view - 20, cao 50
segmentedControl.frame = CGRect(x: 10, y: 250, width: view.frame.width - 20, height: 50)
// Thêm action cho event valueChanged
segmentedControl.addTarget(self, action: #selector(segmentChanged(_:)), for: .valueChanged)
// Chọn mặc định segment index 1 (Second)
segmentedControl.selectedSegmentIndex = 1
// Thêm vào view
view.addSubview(segmentedControl)
}
Xử lý action
@objc func segmentChanged(_ sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0:
print("First segment selected")
// Cập nhật UI cho segment 1
case 1:
print("Second segment selected")
case 2:
print("Third segment selected")
default:
break
}
}
Gọi trong viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
addSegmentedControl()
}
Kết quả

Tuỳ chỉnh giao diện (iOS 13+)
// Màu nền cho segment được chọn
segmentedControl.selectedSegmentTintColor = .systemBlue
// Text attributes cho normal/selected
let normalAttrs: [NSAttributedString.Key: Any] = [
.font: UIFont.systemFont(ofSize: 16, weight: .medium),
.foregroundColor: UIColor.label
]
let selectedAttrs: [NSAttributedString.Key: Any] = [
.font: UIFont.systemFont(ofSize: 16, weight: .semibold),
.foregroundColor: UIColor.white
]
segmentedControl.setTitleTextAttributes(normalAttrs, for: .normal)
segmentedControl.setTitleTextAttributes(selectedAttrs, for: .selected)
// Background image (tuỳ chọn)
segmentedControl.setBackgroundImage(UIImage(color: .systemGray5), for: .normal, barMetrics: .default)
segmentedControl.setDividerImage(UIImage(), forLeftSegmentState: .normal, rightSegmentState: .normal, barMetrics: .default)
Lưu ý: Nên dùng Auto Layout (constraints) thay vì frame cứng để thích ứng mọi kích thước màn hình.