一、创建控件,并监听控件选择值
/*选项除了文字还可以是图片 as关键字的作用就是字面意思:类型转换*/let items = ["选项一", "选项二", UIImage(named: "Icon_58")!] as [Any] let segmented = UISegmentedControl(items:items) segmented.center = self.view.center segmented.selectedSegmentIndex = 1 //默认选中第二项 segmented.addTarget(self, action: #selector(ViewController.segmentDidchange(mysegment:)),for: .valueChanged) //添加值改变监听 self.view.addSubview(segmented)
方法的实现
func segmentDidchange(mysegment:UISegmentedControl){ //获得选项的索引 print(mysegment.selectedSegmentIndex) //获得选择的文字 print(mysegment.titleForSegment(at: mysegment.selectedSegmentIndex)) }
二、其他的属性
//选择空间中选项的添加和删除 segmented.insertSegment(withTitle: "新增选项", at: 2, animated: true) //添加图片选项 segmented.insertSegment(with: UIImage(named:"Icon_58"), at: 2, animated: true) //移除选项 segmented.removeSegment(at: 1, animated: true) //修改选项的颜色(包括图片选项) segmented.tintColor = UIColor.red //修改选项文字/图片 segmented.setTitle("swift", forSegmentAtIndex: 2) segmented.setImage(UIImage(named: "hgl.jpeg"), forSegmentAtIndex: 2) //修改选项内容偏移位置 segmented.setContentOffset(CGSize(width:5,height:10), forSegmentAtIndex: 2)