How to set UISegmentedControl Tint Color for individual segment

Automate This picture Automate This · Mar 28, 2015 · Viewed 28.8k times · Source

Starting to learn Swift and am attempting to convert this ObjectiveC code:

[[mySegmentedControl.subviews objectAtIndex:0] setTintColor:[UIColor blueColor]]

This correctly sets the tint color of the first segment.


This is the closest I've come to getting a Swift version of the same code:

mySegmentedControl?.subviews[0].tintColor = UIColor.blueColor()

The error I get is '@Ivalue $T9' is not identical to 'UIColor!!'


I don't understand what this error means. When I look at the .tintColor method it list UIColor!? and I haven't found what the !? together means in Swift yet.

Answer

Prajeet Shrestha picture Prajeet Shrestha · Mar 28, 2015

This will solve your problem:

var subViewOfSegment: UIView = mySegmentedControl.subviews[0] as UIView
subViewOfSegment.tintColor = UIColor.blueColor()

You can also

(mySegmentedControl.subviews[0] as UIView).tintColor = UIColor .blueColor()