UISegmentedControl selected segment color

Viewed 98064

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?

23 Answers

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+

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];
        }
    }
}

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

[segmentedControl setSelectedSegmentTintColor:[UIColor darkGrayColor]];

//For iOS 13

This Swift 4 code works for me

segmentedControl.setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.red], for: .selected)
Related