Swift UI - 分段选择控件(UISegmentedControl)

注:代码已升级至Swift4

选择控件的创建,并监听控件选择值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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.segmentDidChanged(_:)),
for: .valueChanged) //添加值改变监听
self.view.addSubview(segmented)
}

func segmentDidChanged(_ segmented:UISegmentedControl){
//获得选项的索引
print(segmented.selectedSegmentIndex)
//获得选择的文字
print(segmented.titleForSegment(at: segmented.selectedSegmentIndex))
}
}

选择控件中选项的添加和删除

1
2
3
4
5
6
//添加文字选项
segmented.insertSegment(withTitle: "新增选项", at:1, animated:true);
//添加图片选项
segmented.insertSegment(with: UIImage(named:"icon")!, at:1, animated: true)
//移除选项
segmented.removeSegment(at: 1, animated:true)

修改选项颜色(包括图片选项)

1
segmented.tintColor = UIColor.red

修改选项文字

1
segmented.setTitle("swfit", forSegmentAt:1)

修改选项图片

(1)下面代码图片会自动变成蓝色

1
segmented.setImage(UIImage(named:"icon"), forSegmentAt:2)

(2)使用下面代码,图标保留原来的颜色

1
segmented.setImage(UIImage(named:"icon")?.withRenderingMode(.alwaysOriginal), forSegmentAt:2)

修改选项内容偏移位置

1
segmented.setContentOffset(CGSize(width:10, height:7), forSegmentAt:1)

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :