在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() { super.viewDidLoad() // 选择空间的创建, 并监听控件的选择值 let items = ["选项1","选项2",UIImage.init(named: "1.png")!] as [Any]
let segment = UISegmentedControl.init(items: items) segment.center = self.view.center segment.selectedSegmentIndex = 1 // 默认选中项
segment.addTarget(self, action: #selector(didSeleted(sender:)), for: .valueChanged)
self.view.addSubview(segment)
// 添加文字选项 segment.insertSegment(withTitle: "新增选项", at: 1, animated: true)
// 添加图片选项 segment.insertSegment(with: UIImage.init(named: "1"), at: 1, animated: true)
// 移除选项 segment.removeSegment(at: 1, animated: true)
// 修改选项颜色 (包括图片选项) segment.tintColor = UIColor.red
// 修改文字选项 segment.setTitle("swift", forSegmentAt: 1)
// 修改选项图片 // 下面的代码会自动变为蓝色 segment.setImage(UIImage.init(named: "1"), forSegmentAt: 2)
// 使用下面的代码, 图标会保留原来的颜色 segment.setImage(UIImage.init(named: "1")?.withRenderingMode(.alwaysOriginal), forSegmentAt: 2)
// 修改选项内容偏移位置 segment.setContentOffset(CGSize.init(width: 10, height: 7), forSegmentAt: 1)
}
func didSeleted(sender: UISegmentedControl){ print(sender.selectedSegmentIndex); print(sender.titleForSegment(at: sender.selectedSegmentIndex) ?? "没有标题,可能是图片") }
override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. }
} |
请发表评论