Reputation: 28529
I want to set colors for the text and background of UISegmentedControl. So I've four colors to set, the default and selected color of the text and background.
I can use tintColor
and backgroundColor
to set the background. But how to set the default text color, not same as the tint color?
Note: here is swift3 not the older language. I'm a beginner of ios, I just start from the swift3, have no experience of the former language.
Any help will be appreciated.
Upvotes: 22
Views: 18054
Reputation: 1020
Here is a quick way to handle it on storyboard:
extension UISegmentedControl {
@IBInspectable var textSelectedColor: UIColor {
get {
return self.textSelectedColor
}
set {
self.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: newValue], for: .selected)
}
}
@IBInspectable var textNormalColor: UIColor {
get {
return self.textNormalColor
}
set {
self.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: newValue], for: .normal)
}
}}
Upvotes: 1
Reputation: 28529
Here is the workable one:
// 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)
Upvotes: 6
Reputation: 13527
Swift 5+ code to update text color for your UISegmentedControl
(sc
in this example)
// selected option color
sc.setTitleTextAttributes([.foregroundColor: UIColor.green], for: .selected)
// color of other options
sc.setTitleTextAttributes([.foregroundColor: UIColor.white], for: .normal)
Upvotes: 36
Reputation: 7778
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)
Upvotes: 19
Reputation:
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)
Upvotes: 0
Reputation: 3475
UISegmentedControl.appearance().setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.redColor()], forState: .Selected)
Upvotes: 19