【问题标题】:Swift how to set default text color for UISegmentedControl?Swift 如何为 UISegmentedControl 设置默认文本颜色?
【发布时间】:2017-07-28 19:25:02
【问题描述】:
我想为 UISegmentedControl 的文本和背景设置颜色。所以我要设置四种颜色,文本和背景的默认颜色和选定颜色。
我可以使用tintColor 和backgroundColor 来设置背景。但是如何设置默认的文本颜色,而不是色调颜色呢?
注意:这里是 swift3 不是旧语言。我是ios初学者,刚从swift3开始,没有前一种语言的经验。
任何帮助将不胜感激。
【问题讨论】:
标签:
ios
swift
iphone
xcode
uisegmentedcontrol
【解决方案1】:
这是可行的:
// default background color
customSC.backgroundColor = UIColor(red:65/255.0, green:140/255.0, blue:218/255.0, alpha: 1.0)
// selected background color
customSC.tintColor = UIColor(red:65/255.0, green:140/255.0, blue:218/255.0, alpha: 1.0)
// selected title text color
customSC.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.white], for: UIControlState.selected)
// default title text color
customSC.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.darkGray], for: UIControlState.normal)
【解决方案2】:
Swift 5+ 代码为您的UISegmentedControl(在本例中为sc)更新文本颜色
// selected option color
sc.setTitleTextAttributes([.foregroundColor: UIColor.green], for: .selected)
// color of other options
sc.setTitleTextAttributes([.foregroundColor: UIColor.white], for: .normal)
【解决方案3】:
Swift 4.2 +
segmentedControl.tintColor = .black //background
segmentedControl.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.white], for: .selected)
segmentedControl.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.red], for: .normal)
【解决方案4】:
customSC.backgroundColor= UIColor(red: 0.5, greep: 0.5, blue: 0.5, alpha: 1.0)
customSC.tintColor= UIColor(red: 0.5, greep: 0.5, blue: 0.5, alpha: 1.0)
【解决方案5】:
UISegmentedControl.appearance().setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.redColor()], forState: .Selected)