Color unselected segment of UISegmentedControl without hiding selection

Viewed 81

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.

4 Answers

iOS 13 (Xcode 13.4) Segment Control 100% Working

Segmentcontroller selected backgroundColor

mySegmentedControl.selectedSegmentTintColor = .white
let subView = mySegmentedControl.subviews[1] as UIView
subView.layer.backgroundColor = UIColor.yellow.cgColor
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"`
`

You can do it by using the following code:

init(){
    UISegmentedControl.appearance().backgroundColor = .yellow
}

var body: some View{
     your code…
}

if you want to change the selected segment’s color, you can use:

UISegmentedControl.appearance().selectedSegmentTintColor = .blue

to change it. I hope these codes can help you :D

For detail, you can visit here.

Using Apple APIs, you could try drawing an image with the 4 colors and set that as background using setBackgroundImage(_:for:barMetrics:).

Here's some code to draw a 40x10 image with just one color to get you started:

    let rect = CGRect(origin: CGPoint(x: 0, y:0), size: CGSize(width: 40, height: 10))
    UIGraphicsBeginImageContext(rect.size)
    let context = UIGraphicsGetCurrentContext()!

    context.setFillColor(color.cgColor)
    context.fill(rect)

    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

To get an image with your four colors, you need to repeat context.setFillColor(<varying color>) and context.fill(<varying rect>) four times.

The image should stretch, which means you it only needs to have four equally sized colored rectangles; you don't need to create it in the exact size of the segmented control.

You can then set the selected segment color using the selectedSegmentTintColor property.

Related