Search code examples
swiftuisegmentedcontrol

How to set UISegmentedControl Tint Color for individual segment


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.


Solution

  • 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()