通过代码创建 UISegmentedControl
- 创建 UISegmentedControl 的新实例,其中包含 3 个项目(段):
let mySegmentedControl = UISegmentedControl (items: ["One", "Two", "Three"])
- 设置框架;
mySegmentedControl.frame = CGRect(x: 0.0, y: 0.0, width: 300, height: 50)
- 进行默认选择(不是将段索引为 0):
mySegmentedControl.selectedSegmentIndex = 0
- 配置目标:
mySegmentedControl.addTarget(self, action: #selector(segmentedValueChanged(_:)), for: .valueChanged)
5 处理值已更改:
func segmentedValueChanged(_ sender:UISegmentedControl!) {
print("Selected Segment Index is : \(sender.selectedSegmentIndex)")
}
- 将 UISegmentedControl 添加到视图层次结构
yourView.addSubview(mySegmentedControl)