The solution is designed for only two segments, but it can easily be expanded as much as you need. First I suggest creating an enumeration:
enum SegmentedSections: Int { case first, case second }
Then create a function and call this function in viewDidLoad, and also call it every time .valueChanged happens in segmentedControl:
func setProperSegmentedControlColoring(_ segment: UISegmentedControl, type: SegmentedSections) { setSeparatorImages(for: segment, with: type) let subviews = segment.subviews let sortedViews = subviews.sorted(by: { $0.frame.origin.x < $1.frame.origin.x }) for (index, view) in sortedViews.enumerated() { switch type { case .first: if index == segment.selectedSegmentIndex { view.tintColor = .red } else { view.tintColor = .blue } case .second: if index == segment.selectedSegmentIndex { view.tintColor = .blue } else { view.tintColor = .red } } } }
You will also need to change the divider image accordingly:
func setSeparatorImages(for segment: UISegmentedControl, with type: EarnType) { switch type { case .first: let image = UIImage(color: .red) segment.setDividerImage(image, forLeftSegmentState: .selected, rightSegmentState: .normal, barMetrics: .default) case .second: let image = UIImage(color: .blue) segment.setDividerImage(image, forLeftSegmentState: .selected, rightSegmentState: .normal, barMetrics: .default) } }
You will also need an extension for UIImage. You can find it here.
source share