How to Set tint color of text only of selected segment using Swift?

Saqib Omer picture Saqib Omer · Feb 13, 2015 · Viewed 7.7k times · Source

I have used following code to set background of UISegmentedControl.

homeSegment.setDividerImage(UIImage(named: "seperator.png"), forLeftSegmentState: UIControlState.Normal, rightSegmentState: UIControlState.Normal, barMetrics: UIBarMetrics.Default)



homeSegment.setBackgroundImage(UIImage(named: "squareSegment.png"), forState: UIControlState.Selected, barMetrics: UIBarMetrics.Default)
homeSegment.setBackgroundImage(UIImage(named: "squareSegment.png"), forState: UIControlState.Normal, barMetrics: UIBarMetrics.Default)

How can I set text color of selected segment?

Answer

Automate This picture Automate This · Apr 20, 2015

I accomplish this by using setTitleTextAttributes. The example below uses a dictionary to set attributes since you most likely want to set font type and size at the same time. Try this to set your selected segment text color to red:

let segAttributes: NSDictionary = [
       NSForegroundColorAttributeName: UIColor.redColor(), 
                  NSFontAttributeName: UIFont(name: "Avenir-MediumOblique", size: 20)!
]

homeSegment.setTitleTextAttributes(segAttributes as [NSObject : AnyObject], forState: UIControlState.Selected)

Example:

enter image description here