UISegmentedControl setTitleTextAttributes does not work

harinsa picture harinsa · Aug 27, 2013 · Viewed 9.3k times · Source

So I tried to change the text attribute of the title of my UISegmentedControl, but it doesn't work, nothing change. I have also applied a custom background and divider and it works correctly, but not this.

NSDictionary *normaltextAttr = 
            @{[UIColor blackColor]: UITextAttributeTextColor,
              [UIColor  clearColor]: UITextAttributeTextShadowColor,
              [UIFont fontWithName:_regularFont size:20.f]: UITextAttributeFont};


NSDictionary *selectedtextAttr = 
            @{[UIColor colorWithRed:135.0/255.0 green:135.0/255.0 blue:135.0/255.0 alpha:1.0]: UITextAttributeTextColor,
              [UIColor clearColor]: UITextAttributeTextShadowColor,
              [NSValue valueWithUIOffset:UIOffsetMake(0, 1)]: UITextAttributeTextShadowOffset,
              [UIFont fontWithName:_regularFont size:0.0]: UITextAttributeFont};

[[UISegmentedControl appearance] setTitleTextAttributes:normaltextAttr 
                                               forState:UIControlStateNormal];
[[UISegmentedControl appearance] setTitleTextAttributes:selectedtextAttr 
                                               forState:UIControlStateSelected];

Answer

Olivier picture Olivier · Nov 26, 2013

Beware of the difference in how you order your pairs between the factory method (value / key)

[NSDictionary dictionaryWithObjectsAndKeys: value, key, nil]

and the literal declaration (key / value)

@{key: value}

You simply use the wrong order of key and value.

This will work:

NSDictionary *normaltextAttr = 
       @{UITextAttributeTextColor : [UIColor blackColor],
         UITextAttributeTextShadowColor : [UIColor  clearColor],
         UITextAttributeFont : [UIFont fontWithName:_regularFont size:20.f]};


[[UISegmentedControl appearance] setTitleTextAttributes:normaltextAttr forState:UIControlStateNormal];