Reputation: 1533
I'll glad for help.
I know how to change the text for selected state using attributedString, but I can't find a way to set a unique text color(or even background color) for each segment.
Any ideas how to do it?
Upvotes: 1
Views: 148
Reputation: 587
To create unique background color for selected segment you need to create action for UISegmentControl
and then based on the index set the color.
@IBAction func segmentChanged(_ sender: UISegmentedControl) {
if sender.selectedSegmentIndex == 0 {
sender.selectedSegmentTintColor = UIColor.red
} else {
sender.selectedSegmentTintColor = UIColor.blue
}
}
Edit:
So you can try to work with subviews of UISegmentControl
like that:
@IBOutlet weak var segment: UISegmentedControl! {
didSet {
for (index, view) in segment.subviews.enumerated() {
if index == 0 {
view.subviews.forEach{ label in
(label as! UILabel).textColor = UIColor.red
}
} else {
view.subviews.forEach{ label in
(label as! UILabel).textColor = UIColor.blue
}
}
}
}
}
Upvotes: 2