Swift - 分段选择控件(UISegmentedControl)的用法
(本文代码已升级至Swift3)
import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() //选项除了文字还可以是图片 let items = ["选项一", "选项二", UIImage(named: "g1")!] as [Any] let segmented = UISegmentedControl(items:items) segmented.center = self.view.center segmented.selectedSegmentIndex = 1 //默认选中第二项 segmented.addTarget(self, action: #selector(ViewController.segmentDidchange(_:)), for: .valueChanged) //添加值改变监听 self.view.addSubview(segmented) } func segmentDidchange(_ segmented:UISegmentedControl){ //获得选项的索引 print(segmented.selectedSegmentIndex) //获得选择的文字 print(segmented.titleForSegment(at: segmented.selectedSegmentIndex)) } }
//添加文字选项 segmented.insertSegment(withTitle: "新增选项", at:1, animated:true); //添加图片选项 segmented.insertSegment(with: UIImage(named:"icon")!, at:1, animated: true) //移除选项 segmented.removeSegment(at: 1, animated:true)
segmented.tintColor = UIColor.red
segmented.setTitle("swfit", forSegmentAt:1)
(1)下面代码图片会自动变成蓝色
segmented.setImage(UIImage(named:"icon"), forSegmentAt:2)
(2)使用下面代码,图标保留原来的颜色
segmented.setImage(UIImage(named:"icon")?.withRenderingMode(.alwaysOriginal), forSegmentAt:2)
segmented.setContentOffset(CGSize(width:10, height:7), forSegmentAt:1)
航哥,你好。如果添加图片,系统会把它变成蓝色和白色,如何才能保持原来图片的颜色?
更新下呀 都swift3.0了
航哥,你好,按照的方法写一遍,图片怎么没有显示
打扰了,新版swift中 println 已经改成 print了。获取segment选择标题时:segmented.titleForSegmentAtIndex( segmented.selectedSegmentIndex ) 返回 optional,需要加个感叹号。(Xcode7)