Swift UISegmentedControl是一个内容的分组控件,类似于Tag选项卡,下面通过这个swift教程学习一下如何使用UISegmentedControl控件吧!
import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let mySegmentedControl = UISegmentedControl (items: ["One","Two","Three"]) let xPostion:CGFloat = 10 let yPostion:CGFloat = 150 let elementWidth:CGFloat = 300 let elementHeight:CGFloat = 30 mySegmentedControl.frame = CGRect(x: xPostion, y: yPostion, width: elementWidth, height: elementHeight) // 默认选择第2项 mySegmentedControl.selectedSegmentIndex = 1 //UISegmentedControl文本颜色 mySegmentedControl.tintColor = UIColor.yellow //UISegmentedControl背景颜色 mySegmentedControl.backgroundColor = UIColor.black // 添加值改变事件 mySegmentedControl.addTarget(self, action: #selector(ViewController.segmentedValueChanged(_:)), for: .valueChanged) self.view.addSubview(mySegmentedControl) } //实现选择方法 func segmentedValueChanged(_ sender:UISegmentedControl!) { print("Selected Segment Index is : \(sender.selectedSegmentIndex)") } }
上方的UISegmentedControl代码运行结果如下: