发现不是很好用,因为有时候需要图片和文字同时存在,所以一般还是自定义了
/* swift 3.0 UISegmentedControl的使用
1. 创建UISegmentedControl (不仅可以是文字,而且可以是图片)
2. 设置的图片被重新渲染,所以withRenderingMode(.alwaysOriginal)以原图显示
3. 如果对于选中时的背景不喜欢, 可以通过segmented.tintColor = UIColor.red修改
4. segmented.backgroundColor = UIColor.orange 设置未选中的背景色
5. 其他自定义: segmented.titleTextAttributes(for: <#T##UIControlState#>)可以帮你
*/
let items = ["选项一","选项二",UIImage.init(named: "a.png")?.withRenderingMode(.alwaysOriginal)] as [Any]
let segmented = UISegmentedControl.init(items: items)
segmented.center = view.center
segmented.bounds = CGRect.init(x: 0, y: 0, width: 300, height: 100)
segmented.selectedSegmentIndex = 1 //下标从0开始
segmented.addTarget(self, action: #selector(segmentedDidChange), for: .touchUpInside)
segmented.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.green,NSFontAttributeName:UIFont.systemFont(ofSize: 20)], for: .selected)
/* tintColor 必须设置在 backgroundColor之后 */
segmented.backgroundColor = UIColor.yellow
segmented.tintColor = UIColor.clear
segmented.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.red,NSFontAttributeName:UIFont.systemFont(ofSize: 20)], for: .normal)
segmented.layer.borderWidth = 0;
segmented.layer.borderColor = UIColor.green.cgColor;
view.addSubview(segmented)
}
func segmentedDidChange( sender: UISegmentedControl ){
print(sender.selectedSegmentIndex)
}