iosswiftcolorsuisegmentedcontrol

Color unselected segment of UISegmentedControl without hiding selection


I wanted to color each segment in my UISegmentedControl in a different color. I used the following Swift code (there were some changes with segmentedControl in iOS 13):

segmentedControl.selectedSegmentTintColor = .white
let col: UIColor = .yellow
var subViewOfSegment: UIView = segmentedControl.subviews[2] as UIView
subViewOfSegment.layer.backgroundColor = col.cgColor

This works in general, one segment is now coloured. However, the selected segment is not shown anymore. The selected segment is supposed to be white, but it seems to be overlaid by the colour. The following image show how it looks when I select each segment from left to right:

enter image description here

I already tried subViewOfSegment.backgroundColor = col instead (same effect) or subViewOfSegment.tintColor = col (no effect at all in iOS 13) but I can't get the colors without hiding the selection. On other posts I only find this answer which doesn't say how to color unselected segments.


Solution

  • let subViewOfSegment: UIView = segmentedControl.subviews[1] as UIView
    subViewOfSegment.backgroundColor = UIColor.red
    subViewOfSegment.layer.zPosition = -999
    
    > above solution is not proper but one of the way you can achieve it. you need manage one more label while select segment is red"`
    `