สร้าง UISegmentedControl ด้วยโค้ด และเพิ่มลง View Container
โค้ดสร้างและเพิ่ม Segmented Control
func addSegmentedControl() {
let items = ["First", "Second", "Third"]
let segmentedControl = UISegmentedControl(items: items)
// ตำแหน่งและขนาด
segmentedControl.frame = CGRect(x: 20, y: 100, width: view.bounds.width - 40, height: 40)
// สไตล์ (iOS 13+)
segmentedControl.selectedSegmentIndex = 0
segmentedControl.backgroundColor = .systemBackground
segmentedControl.selectedSegmentTintColor = .systemBlue
// Title Attributes
let normalAttrs: [NSAttributedString.Key: Any] = [
.font: UIFont.systemFont(ofSize: 14),
.foregroundColor: UIColor.label
]
let selectedAttrs: [NSAttributedString.Key: Any] = [
.font: UIFont.boldSystemFont(ofSize: 14),
.foregroundColor: UIColor.white
]
segmentedControl.setTitleTextAttributes(normalAttrs, for: .normal)
segmentedControl.setTitleTextAttributes(selectedAttrs, for: .selected)
// Action
segmentedControl.addTarget(self, action: #selector(segmentChanged(_:)), for: .valueChanged)
// เพิ่มลง Container View
containerView.addSubview(segmentedControl)
// Auto Layout (แนะนำ)
segmentedControl.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
segmentedControl.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 20),
segmentedControl.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 20),
segmentedControl.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -20),
segmentedControl.heightAnchor.constraint(equalToConstant: 40)
])
}
@objc func segmentChanged(_ sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0: print("First selected")
case 1: print("Second selected")
case 2: print("Third selected")
default: break
}
// อัปเดต UI / Container View ตาม Segment
}
ใช้กับ Container View Controller
class ParentViewController: UIViewController {
var currentChild: UIViewController?
@objc func segmentChanged(_ sender: UISegmentedControl) {
switchChildViewController(at: sender.selectedSegmentIndex)
}
func switchChildViewController(at index: Int) {
// Remove current
currentChild?.willMove(toParent: nil)
currentChild?.view.removeFromSuperview()
currentChild?.removeFromParent()
// Add new
let newChild: UIViewController
switch index {
case 0: newChild = FirstChildVC()
case 1: newChild = SecondChildVC()
default: newChild = ThirdChildVC()
}
addChild(newChild)
containerView.addSubview(newChild.view)
newChild.view.frame = containerView.bounds
newChild.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
newChild.didMove(toParent: self)
currentChild = newChild
}
}
Storyboard Alternative
ใช้ Segmented Control ใน Storyboard → เชื่อม IBOutlet + IBAction → จัดการ Container View Embed Segue