Xamarin Quick Tip — Changing the UISegmentedControl Text Color

Falafel Software Bloggers
Falafel Software
Published in
2 min readNov 1, 2016

In iOS, the UISegmentedControl is a popular control. It allows you to present your data in an organized, tabbed fashion. When a segment is selected, the text on the segment is changed to the Background Color of the control, this text can sometimes become lost and difficult to read. To get around this problem, this post will show you how to change the UISegmentedControl Text Color when a segment is selected.

UISegmentedControl Color Properties

The UISegmentedControl has some direct color properties, I will outline the most important ones here.

First we have the Tint Color, which is used as the following:

  1. The color of the highlight/background of the selected segment
  2. The text color of the titles on the unselected segments
  3. The color of the control’s overall frame

Next we have the Background Color, which is used as the following:

  1. The background color of unselected segments
  2. The text color of the title of selected segments

Both the Tint Color and Background Color are available as direct properties on the UISegmentedControl itself, and therefore are easy to set. You may encounter an issue where the text becomes lost, or is difficult to read on the selected segment. In this case you may not want to change the entire background color, but only change the Text color on the selected segment to make it more readable. I will show you how to accomplish this.

Setting the UISegmentedControl Text Color for the Selected Segment

What is not straight forward is how to set the Text color of the selected (highlighted) segment. We accomplish this by using UITextAttributes and assigning them to the Title Text Attributes of the control for the corresponding control state, in our case, the selected state.

The following code assumes that you already have a UISegmentedControl and it’s segments defined. This code refers to the control as ‘this.segmentedControl’:

var backgroundColor = UIColor.Clear;
var accentColor = UIColor.Green;
var textColor = UIColor.Blue;

this.segmentedControl.BackgroundColor = backgroundColor;
this.segmentedControl.TintColor = accentColor;

//create a UITextAttributes instance to define a text color for the selected segment
var uita = new UITextAttributes();
uita.TextColor = textColor;

//set the new text color attributes on the selected segment's title
this.segmentedControl.SetTitleTextAttributes(uita, UIControlState.Selected);

This will display a green control with a clear background. When a tab is selected, the text of the selected segment is changed to Blue (instead of Clear) and is much easier to read.

UISegmentedControl Text Color Change

UISegmentedControl Text Color Change

Originally published at Falafel Software Blog.

--

--