73

Is there any way to customize color of selected segment in UISegmentedControl?

I've found segmentedController.tintColor property, which lets me customize color of the whole segmented control. The problem is, when I select bright color for tintColor property, selected segment becomes almost unrecognizable (its color is almost the same as the rest of segmented control, so its hard to distinguish selected and unselected segments). So I cannot use any good bright colors for segmented control. The solution would be some separate property for selected segment color but I cannot find it. Did anyone solve this?

KlimczakM
  • 12,576
  • 11
  • 64
  • 83
Mike
  • 1,712
  • 3
  • 17
  • 17
  • Theoretically this component is designed to prevent this from happening. If you select background color and tint color, this will alternate for the selected and deselected. Ie if you select background black and white tint, when you select one, it will be put with white background and black tint and vice versa. – jose920405 Feb 24 '16 at 20:13
  • https://stackoverflow.com/a/55374590/4061501 – Lal Krishna Mar 27 '19 at 10:08

23 Answers23

74

Here is the absolute simplest way to change the selected segment to any RGB color. No subclassing or hacks required.

segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;

UIColor *newTintColor = [UIColor colorWithRed: 251/255.0 green:175/255.0 blue:93/255.0 alpha:1.0];
    segmentedControl.tintColor = newTintColor;

UIColor *newSelectedTintColor = [UIColor colorWithRed: 0/255.0 green:175/255.0 blue:0/255.0 alpha:1.0];
[[[segmentedControl subviews] objectAtIndex:0] setTintColor:newSelectedTintColor];

This example shows the important steps:

  1. Sets the control style to "StyleBar", which is required for it to work
  2. Sets the un-selected color for the entire control first to orange
  3. Sets the color of the selected segment to green

Notes:

  • Steps 1 and 2 can be done in interface builder, or in code as shown. However step 3 can only be done in code
  • The color values being set with notation like this "123.0/255.0" is just a way to make the RGB values stand out instead the normalized float values required by UIColor (just ignore it if you like)
Besi
  • 22,579
  • 24
  • 131
  • 223
whitneyland
  • 10,632
  • 9
  • 60
  • 68
  • Mad props to you man, for posting up an answer to this old question. I found it and your response helped me out greatly! I already had a segmented control implemented so I merely needed to use the very last line. Works perfectly, thanks! – Stunner Jun 02 '11 at 10:45
  • 9
    @Lee Whitney, I think the index of selected segment is different from the index of the subview of the segmentedcontrol. – Jack Sep 08 '11 at 00:51
  • 5
    Well, this makes too much sense. I just can't get it to click. I created a 2-segment UISegCont in IB, index 0 selected, and assigned the tint to darkgray. I then use the last line to define the color for ALL selected segments. But when the VC appears, the index 0 segment is black and the index 1 segment is darkgray. Then when I click the index 1 segment, the index 0 segment DOES appear in my custom color. Huh? It seems that the colors may need to be defined everytime the UISegCiont state changes. – mputnamtennessee Oct 05 '11 at 02:24
  • 4
    That doesn't work. Setting newTintColor as the tintColor of the whole control is working but setting newSelectedTintColor as the tintColor of the first subview is not doing anything. – Alexis Mar 11 '13 at 11:40
  • 6
    Note: .segmentedControlStyle was deprecated in iOS 7.0 – taber Jul 20 '14 at 18:21
53

I found A Simple Way to Add Color for Selected Segment in UISegmentcontrol

sender is UISegmentControl

for (int i=0; i<[sender.subviews count]; i++) 
{
    if ([[sender.subviews objectAtIndex:i]isSelected] ) 
    {               
    UIColor *tintcolor=[UIColor colorWithRed:127.0/255.0 green:161.0/255.0 blue:183.0/255.0 alpha:1.0];
    [[sender.subviews objectAtIndex:i] setTintColor:tintcolor];
    }
   else 
    {
        [[sender.subviews objectAtIndex:i] setTintColor:nil];
    }
}

Check its Working For Me

jothikenpachi
  • 656
  • 6
  • 12
  • 4
    You should add sanity checks if the subview responds to selectors isSelected and setTintColor or else when Apple changes the way UISegmentedControl works, the code will crash. – srgtuszy Mar 20 '12 at 02:04
  • seems to me like this could get rejected. Anyone tried this code in App Store? – yonix May 02 '12 at 11:38
  • 4
    @yonix: while it seems like a hack-around, it does not use private APIs. It *should* be fine to use. – Tom Fobear Jun 01 '12 at 16:54
  • 2
    This was a good solution, but I found that I needed to also remove the break, and add `else [[sender.subviews objectAtIndex:i] setTintColor:sender.tintColor];` to reset old tint colors – elimirks Jul 04 '13 at 19:43
  • I have tried above code in my app , and its not rejected . i think my target version ios 8 . that's y not rejected – ShujatAli May 03 '15 at 17:37
  • Check setTitleTextAttributes method for UISegmentedControl. for swift check this answer https://stackoverflow.com/a/50722954/1589731 – ayalcinkaya Jun 06 '18 at 14:31
  • 1
    Application got crashed in iOS 13 – Hitesh Surani Apr 08 '20 at 11:02
23

To do this you simply have to find the selected segment, for example by iterating over the segmented control's subviews and testing the isSelected property, then simply call the setTintColor: method on that subview.

I did this by connecting an action to each segmented control on the ValueChanged event in Interface Builder, I connected them to this this method in the view controller file which is essentially msprague's answer:

- (IBAction)segmentedControlValueChanged:(UISegmentedControl*)sender
{
    for (int i=0; i<[sender.subviews count]; i++)
    {
        if ([[sender.subviews objectAtIndex:i] respondsToSelector:@selector(isSelected)] && [[sender.subviews objectAtIndex:i]isSelected])
        {
            [[sender.subviews objectAtIndex:i] setTintColor:[UIColor whiteColor]];
        }
        if ([[sender.subviews objectAtIndex:i] respondsToSelector:@selector(isSelected)] && ![[sender.subviews objectAtIndex:i] isSelected])
        {
            [[sender.subviews objectAtIndex:i] setTintColor:[UIColor blackColor]];
        }
    }
}

To ensure that the control is displayed correctly each time the view is opened by the user I also had to override the -(void)viewDidAppear:animated method and call the method as follows:

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    //Ensure the segmented controls are properly highlighted
    [self segmentedControlValueChanged:segmentedControlOne];
    [self segmentedControlValueChanged:segmentedControlTwo];
}

For some bonus points if you do want to set the segmented control to use a white tint color on selection then you will also want to change the color of the text to black when it's selected, you can do this like so:

//Create a dictionary to hold the new text attributes
NSMutableDictionary * textAttributes = [[NSMutableDictionary alloc] init];
//Add an entry to set the text to black
[textAttributes setObject:[UIColor blackColor] forKey:UITextAttributeTextColor];
//Set the attributes on the desired control but only for the selected state
[segmentedControlOne setTitleTextAttributes:textAttributes forState:UIControlStateSelected];

With the introduction of iOS 6 setting the tint color of the selected item for the first time in the viewDidAppear method wont work, to get around this I used grand central dispatch to change the selected color after a fraction of a second like so:

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.05 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
        [self segmentedControlValueChanged:segmentedControlOne];
    });
David Thompson
  • 2,902
  • 2
  • 18
  • 21
  • thanks for your helpful comment regarding iOS 6. I had code setting the tint color for each segment that stopped working in iOS 6. Your suggestion fixed my problem. – daveywc Oct 01 '12 at 03:42
  • Yeah I noticed that my solution doesn't work for iOS 6. Thanks! – Mike Sprague Dec 04 '12 at 23:17
  • 1
    dispatch_get_current_queue() is deprecated in iOS 6. Use dispatch_get_main_queue() instead. – tadasz Jan 09 '13 at 19:59
  • Thanks @tasasz I meant to update the answer with this when I noticed that and forgot all about it, updated now. Not only is it deprecated dispatch_get_current_queue() should only be used during debugging according to the documentation, along with the fact that UI changes should only occur on the main thread! – David Thompson Jan 13 '13 at 11:29
9

For some reason Apple dont allow you to change the color of standard UISegmentedControls.

There is however a "legal" way around it which is to change the segmented control style to UISegmentedControlStyleBar. This makes it look slightly different which you may not like but it does allow color.

    NSArray *itemArray = [NSArray arrayWithObjects: @"One", @"Two", @"Three", nil];
UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:itemArray];

//Change Bar Style and ad to view then release segmented controller

segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
segmentedControl.tintColor = [UIColor colorWithRed:.9 green:.1 blue:.1 alpha:1]; 
[self.view addSubview:segmentedControl];
[segmentedControl release];

Hope this helped,

Seb Kade "I'm here to help"

Seb Kade
  • 1,933
  • 2
  • 11
  • 7
8

Edit: This solution doesn't work on iOS 6. See David Thompson's answer below.

This thread is really old, but none of the simple answers worked properly for me.

The accepted answer works as long as you revert the color of the deselected segmented controls. Something like this will work in your value changed function:

for (int i=0; i<[control.subviews count]; i++) 
{
    if ([[control.subviews objectAtIndex:i]isSelected] ) 
    {               
        UIColor *tintcolor=[UIColor colorWithRed:127.0/255.0 green:161.0/255.0 blue:183.0/255.0 alpha:1.0];
        [[control.subviews objectAtIndex:i] setTintColor:tintcolor];
    } else {
        UIColor *tintcolor=[UIColor grayColor]; // default color
        [[control.subviews objectAtIndex:i] setTintColor:tintcolor];
    }
}
Mike Sprague
  • 3,567
  • 1
  • 22
  • 25
7

I know this is an old question But now in xcode 11 +, you can set selected segment Tint colour enter image description here

In code us can use selectedSegmentTintColor. available iOS 13+

amar
  • 4,285
  • 8
  • 40
  • 52
  • 1
    Note: If your project was originally created in Xcode 10 or older, you may need to update your Storyboard file's "Opens in" (located in File Inspector) to Xcode 11 in order to see this feature. – Nathan Hosselton Jan 15 '20 at 15:42
6

Here is my modified version of uihacker's CustomSegmentedControl (see credit in comment). The idea is I change the way to find the subview that should have the tintColor changed, from using selectedIndex to isSelected method. Because I was working with a custom UISegmentedControl that has 3 or more segments which the subview ordering changes randomly (even uihacker's "hasSetSelectedIndexOnce" flag doesn't fix this!). The code is still in early dev stage so use it at your own risk. Any comment is welcomed :)

Also, I added support to interface builder, and override setSelectedSegmentIndex so that it also updates the color. Enjoy!

CustomSegmentedControl.h

//
//  CustomSegmentedControl.h
//
//  Created by Hlung on 11/22/54 BE.
//  Copyright (c) 2554 __MyCompanyName__. All rights reserved.
//
//  Credit: http://uihacker.blogspot.com/2010/05/iphone-uisegmentedcontrol-custom-colors.html

@interface CustomSegmentedControl : UISegmentedControl {
    UIColor *offColor,*onColor;
}
@property (nonatomic,retain) UIColor *offColor,*onColor;
-(id)initWithItems:(NSArray *)items offColor:(UIColor*)offcolor onColor:(UIColor*)oncolor;
@end

CustomSegmentedControl.m

#import "CustomSegmentedControl.h"

@interface CustomSegmentedControl (private)
-(void)setInitialMode;
-(void)toggleHighlightColors;
@end

@implementation CustomSegmentedControl

@synthesize offColor,onColor;

-(id)initWithItems:(NSArray *)items offColor:(UIColor*)offcolor onColor:(UIColor*)oncolor {
    if (self = [super initWithItems:items]) {
        // Initialization code
        self.offColor = offcolor;
        self.onColor = oncolor;
        [self setInitialMode];

        // default to 0, other values cause arbitrary highlighting bug
        [self setSelectedSegmentIndex:0];
    }
    return self;
}
- (void)awakeFromNib {
    // default colors
    self.offColor = [UIColor colorWithWhite:0.8 alpha:1];
    self.onColor = self.tintColor;
    [self setInitialMode];

    [self setSelectedSegmentIndex:0];
}

-(void)setInitialMode
{
    // set essential properties
    [self setBackgroundColor:[UIColor clearColor]];
    [self setSegmentedControlStyle:UISegmentedControlStyleBar];

    // loop through children and set initial tint
    for( int i = 0; i < [self.subviews count]; i++ )
    {
        [[self.subviews objectAtIndex:i] setTintColor:nil];
        [[self.subviews objectAtIndex:i] setTintColor:offColor];
    }

    // listen for updates, [self setSelectedSegmentIndex:0] triggers UIControlEventValueChanged in 5.0, 4.3 doesn't (facepalm), use  if( self.window ) to fix this
    [self addTarget:self action:@selector(toggleHighlightColors) forControlEvents:UIControlEventValueChanged];
}

// ---------------
// hlung's version
// ---------------
-(void)toggleHighlightColors
{
    // the subviews array order randomly changes all the time, change to check for "isSelected" instead
    for (id v in self.subviews) {
        if ([v isSelected]) [v setTintColor:onColor];
        else [v setTintColor:offColor];
    }
}
// override: update color when set selection
- (void)setSelectedSegmentIndex:(NSInteger)selectedSegmentIndex {
    [super setSelectedSegmentIndex:selectedSegmentIndex];
    [self toggleHighlightColors];
}
// ---------------
@end
Hlung
  • 13,850
  • 6
  • 71
  • 90
  • its worked but i have a question on viewdidload method my segmented control is coming with defaults colors. after giving action to any segment index, segments changed their color but i need this initially because at the very first viewdidload calling. how it is possible? – Anju Aug 04 '12 at 07:01
  • add this to your uisegmented subclass : -(void) drawRect:(CGRect)rect { [super drawRect:rect]; [self toggleHighlightColors]; } – Vassily Oct 10 '12 at 07:42
  • @Annie did @Vassily 's suggestion solve it? Or you can try calling `- (void)setSelectedSegmentIndex:(NSInteger)selectedSegmentIndex` in your `viewDidLoad` :) – Hlung Dec 26 '12 at 07:45
  • @DeZigny glad you like it :D – Hlung Dec 26 '12 at 07:46
3

Use this:

[[UISegmentedControl appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor colorWithRed:255.0/255 green:37.0/255 blue:99.0/255 alpha:1.0]} forState:UIControlStateSelected];
Marin Atanasov
  • 3,266
  • 3
  • 35
  • 39
user3272090
  • 126
  • 5
2

To clarify the answer provided above by @jothikenpachi we found the following UISegmentController category worked well in iOS6 and allows for an arbitrary on/off color scheme on segments. Plus it will fail gracefully if the private methods isSelected/setTintColor: are changed in future OS releases. Caveats around private API calls, etc.

@implementation UISegmentedControl(CustomTintExtension) {
-(void) updateCustomTintColorOn:(UIColor*)onColor Off:(UIColor*)offColor {
// Convenience function to rest the tint colors after selection, called upon change of selected index

SEL tint = @selector(setTintColor:);

for (UIView *view in [self subviews]) {
    // Loop through the views...
    if (view && ([view respondsToSelector:tint])) {
        [view performSelector:tint withObject:nil];
    }
    if (view && ([view respondsToSelector:tint])) {
        [view performSelector:tint withObject:offColor];
    }
}

// Checking if segment subview is selected...
SEL isSelected = @selector(isSelected);
for (UIView *view in [self subviews]) {
    if ([view respondsToSelector:isSelected] && [view performSelector:isSelected withObject:nil])
    {
        [view performSelector:tint withObject:onColor];
        break;
    }
}

}

Note, this category method would be called from within the UISegmentController's - (IBAction) segmentAction: (id)sender method.

Also note that with iOS6 it seems you may need to call this method initially in the governing UIViewController's - (void)viewDidAppear:(BOOL)animated which may result in a animation flash. To minimize this, try setting the "offColor" as the UISegmentController's tintColor in IB.

MoFlo
  • 559
  • 4
  • 6
2

I just ran into this issue on iOS 7, which works differently than iOS6.

In iOS 7, the color of the label for the selected segment is the same color as the UISegementControl background. The only way to change it on iOS 7 is to set the background color of the UISegmentControl.

segmentControl.backgroundColor = customColor;
Barlow Tucker
  • 6,229
  • 3
  • 36
  • 42
2

I used this and it changed all the colors in one step.

mySegmentedControl.tintColor = [UIColor redColor]
Community
  • 1
  • 1
smDeveloper
  • 1,068
  • 9
  • 12
2

Not sure if this will get approved by the app store, but I wrote a subclass to UISegmentedControl that lets you set a custom selected and unselected color. Check the notes for more info:

http://uihacker.blogspot.com/2010/05/iphone-uisegmentedcontrol-custom-colors.html

cacheflowe
  • 759
  • 9
  • 9
1

The top two solutions didn't work for me when switching between segments.

My solution was to handle the segment change event in my view controller and then call this method each time the segment is changed:

+ (void)setSegmentedControl:(UISegmentedControl *)segmentedControl 
              selectedColor:(UIColor *)selectedColor 
            deselectedColor:(UIColor *)deselectedColor
{
    for (int i = 0; i < segmentedControl.subviews.count; i++) 
    {
        id subView = [segmentedControl.subviews objectAtIndex:i];

        if ([subView isSelected])
            [subView setTintColor:selectedColor];
        else
            [subView setTintColor:deselectedColor];
    }    
}
Brandon O'Rourke
  • 24,165
  • 16
  • 57
  • 58
1

I am wondering why anyone have not mentioned about UIAppearanceProxy

Apple Doc::

https://developer.apple.com/documentation/uikit/uisegmentedcontrol#1653545

Sample Code:

    private class func applyUISegmentControlAppearance(){
    let apperance = UISegmentedControl.appearance()

    // Set Navigation bar Title colour
    let unselAttrib = [NSForegroundColorAttributeName:UIColor.yellow,
                                        NSFontAttributeName: UIFont.systemFont(ofSize: 15)]

    let selAttrib = [NSForegroundColorAttributeName:UIColor.red,
                     NSFontAttributeName: UIFont.boldSystemFont(ofSize: 15)]


    apperance.setTitleTextAttributes(unselAttrib, for: .normal)
    apperance.setTitleTextAttributes(selAttrib, for: .selected)
}

Call From: You can call this method in AppDelegate from

application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool

geekay
  • 1,655
  • 22
  • 31
1

I found I could use tag on the subviews with the same index as the segments, so that in any order they the segments will be colored correctly.

// In viewWillAppear set up the segmented control 

// then for 3 segments:  
self.navigationItem.titleView = segmentedControl;
//Order of subviews can change randomly!, so Tag them with same index as segment
[[[segmentedControl subviews]objectAtIndex:0]setTag:0]; 
[[[segmentedControl subviews]objectAtIndex:1]setTag:1];
[[[segmentedControl subviews]objectAtIndex:2]setTag:2];


// color follows the selected segment
- (IBAction)mySelector:(id)sender {
selector = [sender selectedSegmentIndex]
  for (id seg in [segmentedControl subviews]) {
    for (id label in [seg subviews]) {
        if ([seg tag] == selector){
            [seg setTintColor:selectedColor];
        } else {
            [seg setTintColor:nonSelectedColor];
        }
    }
  }
}

// in viewDidAppear for returning to the view
[segmentedControl setSelectedSegmentIndex:selector];
for (id seg in [segmentedControl subviews]) {
    for (id label in [seg subviews]) {
        if ([seg tag] == selector){
            [seg setTintColor:selectedColor];
        } else {
            [seg setTintColor:nonSelectedColor];
        }
    }
}
RexMac66
  • 111
  • 1
  • 9
0

I found the answers above very helpful. I am using the segmented control to set the precision of a knob. I took a hybrid of the answers above and came up with this:

-(void) viewDidLoad {

NSArray *segments = [NSArray arrayWithObjects:@"Course", @"Fine",nil];

[knob setPrecision:0.1]; // initial precision
// Set starting values

UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:segments];

segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
segmentedControl.frame = CGRectMake(120, 680, 228, 30);
[segmentedControl addTarget:self action:@selector(precisionSelect:) forControlEvents:UIControlEventValueChanged];
segmentedControl.momentary = YES;

[self.view addSubview:segmentedControl];
}   

- (void)precisionSelect:(UISegmentedControl*)sender
{   
    UIColor *tintcolor = [UIColor darkGrayColor];   
    if (sender.selectedSegmentIndex == 0) {
        [[sender.subviews objectAtIndex:0] setTintColor:nil];
        [[sender.subviews objectAtIndex:1] setTintColor:tintcolor];
    [knob setPrecision:0.1]; // Coarse
    } else {
        [[sender.subviews objectAtIndex:0] setTintColor:tintcolor];
        [[sender.subviews objectAtIndex:1] setTintColor:nil];
    [knob setPrecision:0.05]; // Fine
    }

}

Hope this helps others.. A key for me, was being able to reset the unselected index using: setTintColor:nil];

ICL1901
  • 7,632
  • 14
  • 90
  • 138
0

For doing your kind of thing, one might have to access the undocumented features and hacks, which will certainly make apple furious, and that may lead to the rejection of your application.

Now, the solution lies in other trick that you use two buttons instead and have their images interchanged when they are clicked. Keep the buttons closer and images of half segmented control to give the illusion of segmented control and that is all I can suggest you.

Hope this helps.

Thanks,

Madhup

Madhup Singh Yadav
  • 8,110
  • 7
  • 51
  • 84
  • yeah, thanks, guess using UIButtons that look like segmented control is the only way to go if you want custom colors... – Mike Feb 16 '10 at 04:38
  • @Mike: I also think so. May be somebody suggest some other solution which is not a hack and uses the documented api indeed. – Madhup Singh Yadav Feb 16 '10 at 04:43
0
- (IBAction)segmentControlValueChanged:(UISegmentedControl *)sender
{
    if ([[sender.subviews firstObject] respondsToSelector:@selector(setTintColor:)]) {
        for (id segment in sender.subviews) {
            if ([segment respondsToSelector:@selector(isSelected)] && [segment isSelected]) {
                [segment setTintColor:[UIColor redColor]];
            } else {
                [segment setTintColor:[UIColor grayColor]];
            }
        }
    }
}
0
Try this solution.    

enter image description here

enter image description here

        @IBAction func dashBoardSegmentValueChanged(sender: AnyObject) {
            switch dashBoardSegment.selectedSegmentIndex
            {
            case 0:     
                sender.subviews.last?.backgroundColor = UIColor.whiteColor()
                sender.subviews.first?.backgroundColor =  UIColor.clearColor()

                break;
            case 1:            
                sender.subviews.first?.backgroundColor =  UIColor.whiteColor()
                sender.subviews.last?.backgroundColor = UIColor.clearColor()
                break;
            default:
                break;
            }
        }

Note: Make sure you select one segment subview as initial selected for easiness. It works if you have two segment subviews.
Alvin George
  • 14,148
  • 92
  • 64
  • 1
    Why hard-coded ? This all can be done via the Storyboard – OhadM Jul 04 '16 at 14:29
  • Giving an upvote for the basic idea of digging into the subviews and changing the backgroundColor there. It's undocumented behavior, but gives a simple solution for me to control individual segment background colors. (Objective-C: sender.subviews[0].backgroundColor) – Jeff Nov 30 '18 at 22:53
0
- (IBAction)segmentedControlValueChanged:(UISegmentedControl *)sender {
    for (int i = 0; i < sender.subviews.count; i++) {
        UIControl *component = [sender.subviews objectAtIndex:i];
        if ([component respondsToSelector:@selector(isSelected)]) {
            UIColor *selectedColor = [UIColor greenColor];
            UIColor *normalColor   = [UIColor blackColor];
            UIColor *tint = component.isSelected ? selectedColor : normalColor;
            [component setTintColor:tint];
        }
    }
}
Ted
  • 22,696
  • 11
  • 95
  • 109
0
[segmentedControl setSelectedSegmentTintColor:[UIColor darkGrayColor]];

//For iOS 13
Aditi Patil
  • 209
  • 2
  • 3
  • 2
    Please don't post only code as an answer, but include an explanation what your code does and how it solves the problem of the questions. Answers with an explanation are generally of higher quality, and more likely to attract upvotes. – Mark Rotteveel Sep 27 '19 at 18:07
0

You can tag each of the segments, then set the TintColor forTag:

#define kTagOffState 0
#define kTagOnState  2

#define UIColorFromRGB(rgbValue) [UIColor \
        colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 \
        green:((float)((rgbValue & 0xFF00) >> 8))/255.0 \
        blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]

//usage     UIColor color = UIColorFromRGB(0xF7F7F7);

 UIColor onColor = UIColorFromRGB(0xF7F7F7);
 UIColor offColor = UIColorFromRGB(0x878787);

        [multiStateControl setTag:kTagOffState forSegmentAtIndex:0];
        [multiStateControl setTag:kTagOnState forSegmentAtIndex:1];
        [multiStateControl setTintColor:onColor forTag:kTagOnState];
        [multiStateControl setTintColor:offColor forTag:kTagOffState];  
scooter133
  • 1,297
  • 1
  • 15
  • 29
-1

This Swift 4 code works for me

segmentedControl.setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.red], for: .selected)
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
ayalcinkaya
  • 3,303
  • 29
  • 25