Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change font color of UISegmentedControl

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?

like image 402
Oksana Avatar asked Jan 27 '12 06:01

Oksana


People also ask

How do I change the color of my text font?

Go to Format > Font > Font. + D to open the Font dialog box. Select the arrow next to Font color, and then choose a color.

How do I change the background color in Uisegmentedcontrol?

To change the overall color of the segmented control use its backgroundColor . To change the color of the selected segment use selectedSegmentTintColor . To change the color/font of the unselected segment titles, use setTitleTextAttributes with a state of . normal / UIControlStateNormal .


2 Answers

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]; 
like image 151
pbibergal Avatar answered Oct 13 '22 15:10

pbibergal


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) 
like image 34
i-- Avatar answered Oct 13 '22 15:10

i--