Search code examples
iosswiftuisegmentedcontrol

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?


Solution

  • 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