iOS UISegmentedControl swift3.0 发表于 2016-11-05 | 分类于 Mobile | 评论数: | 阅读次数: iOS UISegmentedControl swift3.0 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677//先创建一个数组用于设置分段控件的标题let appsArray:[String] = ["1111","2222","3333","4444","5555"]//创建分段控件let segment:UISegmentedControl = UISegmentedControl(items: appsArray)//设置坐标大小segment.frame = CGRect(x: 20, y: 100, width: 320, height: 40)//添加到视图上self.view.addSubview(segment)//----------------- 分段控件常用属性和方法//默认选中下标为1的segment.selectedSegmentIndex = 1//获取选中的坐标let index = segment.selectedSegmentIndex//设置下标等于2的标题segment.setTitle("Bird Flying", forSegmentAt: 2)//设置下标等于3的图片,图片和标题不能共存,设置图片之后,原来标题就不显示了segment.setImage(UIImage(named: "segmentImage.png"), forSegmentAt: 3)//在坐标为2的位置,插入一个分段标题segment.insertSegment(withTitle: "考试导航", at: 2, animated: true)//在坐标为4的位置,插入一个分段图片 segment.insertSegmentWithImage(UIImage(named: "segmentImage.png")!, atIndex: 4, animated: true)//获取segment的数量let count = segment.numberOfSegments;print(count)//获取某一个下标下的标题let title = segment.titleForSegment(at: 1)//获取某一个下标下得图片let image = segment.imageForSegment(at: 2)//momentary默认为NO点击之后一直处于选中状态,除非点击其他分段,才恢复。 当设置为YES时,点击选中,但一会就是恢复到正常状态。segment.isMomentary = true;//设置某一分段是否可用 segment.setEnabled(false, forSegmentAtIndex: 1)//设置下标为2的segment的宽度segment.setWidth(80, forSegmentAt: 2)//获取某一个下标segment的宽度let width = segment.widthForSegment(at: 2)//设置内容偏移segment.setContentOffset(CGSize(width: 10, height: 10), forSegmentAt: 2)//获取某一个下标segment的内容偏移let size = segment.contentOffsetForSegment(at: 2)//是否根据segment的内容改变segment的宽度segment.apportionsSegmentWidthsByContent = true//设置标题颜色segment.tintColor = UIColor.red//获取颜色let segmentColor = segment.tintColor//移除下标是2的segment segment.removeSegmentAtIndex(2, animated: true)//移出所有segment segment.removeAllSegments()//添加事件,当segment改变时,触发segment.addTarget(self, action: #selector(ViewController.segmentChange(_:)), for: UIControlEvents.valueChanged) 1234567891011121314151617//segemnet选择改变事件func segmentChange(_ sender: AnyObject?){ // var segment:UISegmentedControl = sender as UISegmentedControl let segment:UISegmentedControl = sender as! UISegmentedControl switch segment.selectedSegmentIndex { case 0 : print("000 ") case 1 : print("11111 ") case 2 : print("2222 ") default: print("default ") }} GitHub下载地址