创建UISegmentedControl
let items = ["选项一","选项二","选项三"] let segmented = UISegmentedControl(items: items) segmented.frame = CGRectMake(40, 20, 300, 35) self.view.addSubview
设置
segmented.selectedSegmentIndex = 0//默认选择第一项 segmented.addTarget(self, action: "segmentDidChange:", forControlEvents: UIControlEvents.ValueChanged) segmented.setEnabled(false, forSegmentAtIndex: 1)//变灰无法选择
func segmentDidChange(segmented: UISegmentedControl){ print(segmented.selectedSegmentIndex) if (segmented.titleForSegmentAtIndex(segmented.selectedSegmentIndex) != nil){//选项名称 print(segmented.titleForSegmentAtIndex(segmented.selectedSegmentIndex)!) } // segmented.setContentOffset(CGSizeMake(5, 5), forSegmentAtIndex: segmented.selectedSegmentIndex)//修改选项内容偏移位置 }
选项的添加和删除
segmented.insertSegmentWithTitle("新增选项", atIndex: 1, animated: true)//添加新的选项 segmented.insertSegmentWithImage(UIImage(named: "00000"), atIndex: 2, animated: true) segmented.removeSegmentAtIndex(2, animated: false)//删除选项卡 segmented.setTitle("swift", forSegmentAtIndex: 1)//修改选项文字