UISegmentedControl的使用
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.setupSegmentedControl()
}
func setupSegmentedControl() {
// 创建segmentedControl
let items = ["Hello", "world"]
let segmentedControl = UISegmentedControl(items: items)
segmentedControl.center = self.view.center
// 选项颜色
segmentedControl.tintColor = UIColor.red
// 默认选中第二项
segmentedControl.selectedSegmentIndex = 1
// 点击事件
segmentedControl.addTarget(self, action: #selector(segmentedControlChange(_ :)), for: .valueChanged)
self.view.addSubview(segmentedControl)
// 添加文字选项
segmentedControl.insertSegment(withTitle: "新增", at: 1, animated: true)
// 添加图片选项
let image = UIImage(named: "icon")
segmentedControl.insertSegment(with: image, at: 1, animated: true)
// 修改选项文字
segmentedControl.setTitle("啊哈哈", forSegmentAt: 0)
// 修改选项图片
segmentedControl.setImage(image, forSegmentAt: 1)
// 修改选项内容偏移位置
let size = CGSize(width: 10, height: 7)
segmentedControl.setContentOffset(size, forSegmentAt: 2)
}
func segmentedControlChange(_ segmented: UISegmentedControl) {
if segmented.selectedSegmentIndex == 0 {
print("第0个啊哈哈")
}
else if segmented.selectedSegmentIndex == 1 {
print("第1个啊哈哈")
}
else {
print("其他啊哈哈")
}
}
}