Reputation: 415
How can I change the text color of just one specific segment of a UISegmentedControl? I want to keep them all normal, except for a specific segment which should be a different color, whether it is selected or not.
Upvotes: 4
Views: 7485
Reputation: 5078
for swift 5:
segmentControl.setTitleTextAttributes( [NSAttributedString.Key.foregroundColor: UIColor.white], for: .selected)
Upvotes: 2
Reputation: 39
@IBDesignable
class DesignableSegmentControl: UISegmentedControl{
}
extension UISegmentedControl{
@IBInspectable
var textColor: UIColor{
get {
return self.textColor
}
set {
let unselectedAttributes = [NSAttributedString.Key.foregroundColor: newValue,
NSAttributedString.Key.font: UIFont.systemFont(ofSize: 13, weight: UIFont.Weight.regular)]
self.setTitleTextAttributes(unselectedAttributes, for: .normal)
self.setTitleTextAttributes(unselectedAttributes, for: .selected)
}
}
}
Just change you segment control's class name as shown below:
Upvotes: 3
Reputation: 1566
Updated Swift 4.1
UISegmentedControl.appearance().setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.red], for: .selected)
Swift 3.1
UISegmentedControl.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.red as Any], for: .selected)
For Earlier Swift Version:
UISegmentedControl.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.red], for: .selected)
Upvotes: 1
Reputation: 924
You can implement your own segmented control for customisation.
In this way there is large scope for customisation. Also there are many custom segmented control are available at GitHub. You can try this
https://github.com/gmarm/BetterSegmentedControl
Upvotes: 0
Reputation: 535989
There isn't any built-in way; as you've probably figured out, setTitleTextAttributes
applies to all the segments. You would have to draw your text as an image and use that instead.
Upvotes: 1