90

I try to change font color from white to black for UISegmentedControl (for iOS 4.*)

UISegmentedControl *button = [[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:itemTitle, nil]] autorelease];
button.momentary = YES;
button.segmentedControlStyle = UISegmentedControlStyleBar;
button.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] initWithCustomView:button] autorelease];

But text color does not changed. What I should do for change text color for UISegmentedControl?

Costique
  • 23,712
  • 4
  • 76
  • 79
Oksana
  • 13,442
  • 10
  • 53
  • 89

12 Answers12

131

In iOS 6.0 and above it's very simple:

NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
                            [UIFont boldSystemFontOfSize:17], NSFontAttributeName,
                            [UIColor blackColor], NSForegroundColorAttributeName,
                            nil];
[_segmentedControl setTitleTextAttributes:attributes forState:UIControlStateNormal];
NSDictionary *highlightedAttributes = [NSDictionary dictionaryWithObject:[UIColor whiteColor] forKey:NSForegroundColorAttributeName];
[_segmentedControl setTitleTextAttributes:highlightedAttributes forState:UIControlStateSelected];
nalexn
  • 10,615
  • 6
  • 44
  • 48
pbibergal
  • 2,901
  • 1
  • 17
  • 19
  • any idea about changing font type? – Vaibhav Saran Apr 24 '13 at 05:57
  • `[UIFont fontWithName:@"HelveticaNeue" size:17.0f]` – pbibergal Apr 25 '13 at 08:34
  • Any ideas what might cause this not to work? As an experiment, I set the text color to green, but everything is still the defaults (Grey text on pale-grey background, or white text on blue background if highlighted. That's iOS6. iOS7 is default white/clear.) Thanks! – Olie Mar 18 '14 at 16:28
  • a detailed description given at http://datacalculation.blogspot.in/2014/10/how-to-change-uisegmentedcontrol-text.html – iOS Test Oct 07 '14 at 04:18
  • 10
    Testing on iOS 8.1, the last line to this answer should change from `UIControlStateHighlighted` to `UIControlStateSelected` to achieve the desired effect. – eager to learn Jan 06 '15 at 18:49
  • Is it possible for a single Segment? – Ofir Malachi Aug 15 '17 at 11:39
93

If you need to change the text color of the highlighted segment in iOS 7, here is a solution (took me awhile to find, but thanks to this post):

Objective-C

[[UISegmentedControl appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor blackColor]} forState:UIControlStateSelected];

Swift

  let titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]  
  UISegmentedControl.appearance().setTitleTextAttributes(titleTextAttributes, forState: .Selected)
Community
  • 1
  • 1
i--
  • 4,349
  • 2
  • 27
  • 35
  • Great. You can follow a detailed info at http://datacalculation.blogspot.in/2014/10/how-to-change-uisegmentedcontrol-text.html – iOS Test Oct 07 '14 at 04:21
  • This answer finally helped me completing the requirements on the selection button of my App, previously including a way of keeping the segmented control in a super uiview to make the border square.... – KoreanXcodeWorker May 04 '16 at 06:13
  • 3
    For Swift 5: `var titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white] UISegmentedControl.appearance().setTitleTextAttributes(titleTextAttributes, for: .normal)` – Eric Jan 07 '21 at 06:28
83

code to set both states font color to black

Swift 5

    let titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.black]
    segmentedControl.setTitleTextAttributes(titleTextAttributes, for: .normal)
    segmentedControl.setTitleTextAttributes(titleTextAttributes, for: .selected)

Swift 4

    let titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.black]
    segmentedControl.setTitleTextAttributes(titleTextAttributes, for: .normal)
    segmentedControl.setTitleTextAttributes(titleTextAttributes, for: .selected)
kuzdu
  • 7,124
  • 1
  • 51
  • 69
Ilja Popov
  • 1,091
  • 8
  • 8
  • Does not work for iOS 13 and Swift 5, Xcode can't recognize `segmentedControl` anymore – Sky Dec 31 '19 at 08:59
  • 1
    @Sky, just add a bit of bug fix on my app's segmentedControl today, and this solution is worked on iOS 13.2 and Swift5. – Zhou Haibo Jan 13 '20 at 08:19
31

Below is the code to set the font to the bold face and point size:

UIFont *Boldfont = [UIFont boldSystemFontOfSize:12.0f];
NSDictionary *attributes = [NSDictionary dictionaryWithObject:Boldfont
                                                       forKey: NSFontAttributeName];
[segmentedControl setTitleTextAttributes:attributes 
                                forState:UIControlStateNormal];

I hope it helps

Nimit Parekh
  • 16,776
  • 8
  • 50
  • 72
  • 5
    Caution: this answer requires iOS 5. – Costique Jan 31 '12 at 19:14
  • 1
    This answer doesn't change the font color as the topic starter requested, just the font size. pbibergal's answer is more complete. – Terrabythia Dec 19 '12 at 16:09
  • This works, but warning is coming for UITextAttributeFont is deprecated. Instead use "NSFontAttributeName". All thanks to @johngraham from http://stackoverflow.com/questions/2280391/change-font-size-of-uisegmentedcontrol – mavericks Sep 22 '15 at 10:29
21

Updated for iOS 14 and Swift 5:

extension UISegmentedControl
{
    func defaultConfiguration(font: UIFont = UIFont.systemFont(ofSize: 12), color: UIColor = UIColor.white)
    {
        let defaultAttributes = [
            NSAttributedString.Key.font: font,
            NSAttributedString.Key.foregroundColor: color
        ]
        setTitleTextAttributes(defaultAttributes, for: .normal)
    }

    func selectedConfiguration(font: UIFont = UIFont.boldSystemFont(ofSize: 12), color: UIColor = UIColor.red)
    {
        let selectedAttributes = [
            NSAttributedString.Key.font: font,
            NSAttributedString.Key.foregroundColor: color
        ]
        setTitleTextAttributes(selectedAttributes, for: .selected)
    }
}

Updated for Swift 4 - Use this Extension (because extension is always awesome..!!)

extension UISegmentedControl {

func defaultConfiguration(font: UIFont = UIFont.systemFont(ofSize: 12), color: UIColor = UIColor.gray) {
    let defaultAttributes = [
        NSAttributedStringKey.font.rawValue: font,
        NSAttributedStringKey.foregroundColor.rawValue: color
    ]
    setTitleTextAttributes(defaultAttributes, for: .normal)
}

func selectedConfiguration(font: UIFont = UIFont.boldSystemFont(ofSize: 12), color: UIColor = UIColor.red) {
    let selectedAttributes = [
        NSAttributedStringKey.font.rawValue: font,
        NSAttributedStringKey.foregroundColor.rawValue: color
    ]
    setTitleTextAttributes(selectedAttributes, for: .selected)
}
}

and from the respective class, you can use these function,

@IBOutlet weak var segment: UISegmentedControl!

segment.defaultConfiguration()
// or provide paramater as per your requirement
segment.selectedConfiguration(color: .blue)
Moritz Schaub
  • 91
  • 1
  • 9
Soumen
  • 2,070
  • 21
  • 25
7

in Swift 5 you can change color with this syntax

Swift 5

let titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.red]
groupSegment.setTitleTextAttributes(titleTextAttributes, for: .selected)
mohsen
  • 4,698
  • 1
  • 33
  • 54
7

Swift 5 Extension

extension UISegmentedControl {

    func setTitleColor(_ color: UIColor, state: UIControl.State = .normal) {
        var attributes = self.titleTextAttributes(for: state) ?? [:]
        attributes[.foregroundColor] = color
        self.setTitleTextAttributes(attributes, for: state)
    }
    
    func setTitleFont(_ font: UIFont, state: UIControl.State = .normal) {
        var attributes = self.titleTextAttributes(for: state) ?? [:]
        attributes[.font] = font
        self.setTitleTextAttributes(attributes, for: state)
    }

}
Li Jin
  • 1,879
  • 2
  • 16
  • 23
6
for (UIView *v in [[[segment subviews] objectAtIndex:0] subviews]) {
    if ([v isKindOfClass:[UILabel class]]) {
        UILabel *label=(UILabel *)[v retain];
        lable.textColor=[UIColor blackColor];
    }
}

for iOS 3.0 and above

Stéphane Bruckert
  • 21,706
  • 14
  • 92
  • 130
Levitate
  • 69
  • 1
5

Just in case to help someone else that get there and is working using swift.

I will put the two possible ways of doing it. You can change the text attributes in the UIAppearance or directly in the segmented your are working.

The first example setting the attributes in the appearance, this way you will customize all the segmented controls in your app:

    let attributes = [ NSForegroundColorAttributeName : UIColor.grayColor(),
        NSFontAttributeName : UIFont.systemFontOfSize(20)];
    let attributesSelected = [ NSForegroundColorAttributeName : UIColor.blueColor(),
        NSFontAttributeName : UIFont.systemFontOfSize(20)];
    UISegmentedControl.appearance().setTitleTextAttributes(attributes, forState: UIControlState.Normal)
    UISegmentedControl.appearance().setTitleTextAttributes(attributesSelected, forState: UIControlState.Selected)

The second example, directly in the segmented, will customize only this segmented:

    let attributes = [ NSForegroundColorAttributeName : UIColor.grayColor(),
        NSFontAttributeName : UIFont.systemFontOfSize(20)];
    let attributesSelected = [ NSForegroundColorAttributeName : UIColor.blueColor(),
        NSFontAttributeName : UIFont.systemFontOfSize(20)];
    segmented.setTitleTextAttributes(attributes, forState: UIControlState.Normal)
    segmented.setTitleTextAttributes(attributesSelected, forState: UIControlState.Selected)
ggrana
  • 2,335
  • 2
  • 21
  • 31
4

swift 3.2:

let attributes = [
                          NSFontAttributeName : bigTextFont,
                          NSForegroundColorAttributeName : UIColor.blue,
                          ]         
segmentedControl?.setTitleTextAttributes(attributes, for: .normal)

note: if You use a custom background color, you will see a glitch in corners (color will fill outside segments..), so use these line to clip it:

segmentedControl!.layer.cornerRadius = 4.0
segmentedControl!.clipsToBounds = true
ingconti
  • 10,876
  • 3
  • 61
  • 48
2

In iOS 5.0 and later you can use the titleTextAttributes to customize UISegmentedControl objects :

NSDictionary *segmentedControlTextAttributes = @{NSFontAttributeName:[UIFont fontWithName:@"HelveticaNeue" size:18.0], NSForegroundColorAttributeName:[UIColor whiteColor]};
[self.segmentedControl setTitleTextAttributes:segmentedControlTextAttributes forState:UIControlStateNormal];
[self.segmentedControl setTitleTextAttributes:segmentedControlTextAttributes forState:UIControlStateHighlighted];
[self.segmentedControl setTitleTextAttributes:segmentedControlTextAttributes forState:UIControlStateSelected];

Here I set the font to a custom font, font size, color for each state of the UISegmentedControl.

You'll find every possible simple customizations in the Customizing Appearance section of the UISegmentedControl Class Reference.

Dulgan
  • 6,674
  • 3
  • 41
  • 46
1

Im using monotouch. Dont know why, but when View was pushed text color doesnt changed for me. for solve this im just add labels to segment control superview and then change their colours:

public static void SetColoredTittles(this UISegmentedControl s, string[] titles, UIColor selected, UIColor notSelected)
{ 
    var segmentedLabels = new List<UILabel>();
    float width = s.Frame.Width/titles.Length;

    for (int i = 0; i < titles.Length; i++)
    {
        var frame = new RectangleF(s.Frame.X + i*width, s.Frame.Y, width,s.Frame.Height);
        UILabel label = new UILabel(frame);
        label.TextAlignment = UITextAlignment.Center;
        label.BackgroundColor = UIColor.Clear;
        label.Font = UIFont.BoldSystemFontOfSize(12f);
        label.Text = titles[i];
        s.Superview.AddSubview(label);
        segmentedLabels.Add(label);
    }

    s.ValueChanged += delegate
    {
        TextColorChange(s,segmentedLabels, selected, notSelected);
    };
    TextColorChange(s,segmentedLabels, selected, notSelected);
}

static void TextColorChange(UISegmentedControl s, List<UILabel> segmentedLabels, UIColor selected, UIColor notSelected)
{
    for (int i = 0; i < segmentedLabels.Count; i++)
    {
        if(i == s.SelectedSegment) segmentedLabels[i].TextColor = selected;
        else segmentedLabels[i].TextColor = notSelected;
    }
}

and then use it

segmented.SetColoredTittles(new string[] {
            "text1",
            "text2",
            "text3"
        }, UIColor.White,UIColor.DarkGray);
John
  • 1,447
  • 15
  • 16