Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 567
Automate This Avatar asked Mar 28 '15 01:03

Automate This


People also ask

How do you change the segment control color?

To change the overall color of the segmented control use its backgroundColor . To change the color of the selected segment use selectedSegmentTintColor . To change the color/font of the unselected segment titles, use setTitleTextAttributes with a state of . normal / UIControlStateNormal .

How do I change text color in segmented control?

tintColor = [UIColor redColor]; for (id segment in [button subviews]) { for (id label in [segment subviews]) { if ([label isKindOfClass:[UILabel class]]) { UILabel *titleLabel = (UILabel *) label; [titleLabel setTextColor:[UIColor blackColor]]; } } } UIBarButtonItem *barButtonItem = [[[UIBarButtonItem alloc] ...

How do I change the color of an image in Swift?

SF Symbols. The absolute simplest way to change colors of images (or icons in this case) is to use the SF Symbols where applicaple. This is a set of symbols Apple provides that can easily be used in your own app.


2 Answers

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()
like image 102
Prajeet Shrestha Avatar answered Oct 01 '22 14:10

Prajeet Shrestha


The easiest way I have found is:

segmentControl.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.redColor()], forState: UIControlState.Selected)
like image 23
Adam Gammell Avatar answered Oct 01 '22 14:10

Adam Gammell