Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 503
Saqib Omer Avatar asked Feb 13 '15 10:02

Saqib Omer


1 Answers

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

like image 194
Automate This Avatar answered Oct 04 '22 02:10

Automate This