标签:
一、创建控件,并监听控件选择值
/*选项除了文字还可以是图片 as关键字的作用就是字面意思:类型转换*/ // let items = ["选项一","选项二",UIImage(named:"hgl.jpeg")!] as [AnyObject] let items = ["选项一","选项二"] let segmented = UISegmentedControl(items:items) // segmented.center = self.view.center segmented.frame = CGRectMake(80, 410, SCREEN_WIDTH - 160, 30) segmented.selectedSegmentIndex = 1 //默认选中第二项 segmented.addTarget(self, action: #selector(segmentedClick), forControlEvents: UIControlEvents.ValueChanged)//添加值改变监听 self.view.addSubview(segmented)
方法的实现
func segmentedClick(segmented:UISegmentedControl) { //获得选项的索引 print(segmented.selectedSegmentIndex) //获得选择的文字 print(segmented.titleForSegmentAtIndex(segmented.selectedSegmentIndex)) }
二、其他的属性
//选择空间中选项的添加和删除 segmented.insertSegmentWithTitle("新增选项", atIndex: 2, animated: true) //添加图片选项 segmented.insertSegmentWithImage(UIImage(named: "hgl.jpeg"), atIndex: 1, animated: true) //移除选项 segmented.removeSegmentAtIndex(1, animated: true) //修改选项的颜色(包括图片选项) segmented.tintColor = UIColor.redColor() //修改选项文字/图片 segmented.setTitle("swift", forSegmentAtIndex: 2) segmented.setImage(UIImage(named: "hgl.jpeg"), forSegmentAtIndex: 2) //修改选项内容偏移位置 segmented.setContentOffset(CGSizeMake(5, 3), forSegmentAtIndex: 2)
swift - UISegmentedControl 的用法
标签:
原文地址:http://www.cnblogs.com/hero11223/p/5692215.html