Search code examples
iosuisegmentedcontrol

NSAttributed string for UISegmentedControl


I'm trying to set custom spacing to my UISegmented Control. How can I define the NSKernAttributeName and value attribute to define custom spacing between the letters?

[myUIControl setTitleTextAttributes:@{ NSForegroundColorAttributeName : [UIColor whiteColor], NSFontAttributeName: [UIFont fontWithName:myFont size:13]} forState:UIControlStateSelected];

This is how it is done for a UIButton

[attributedString addAttribute:NSKernAttributeName
                         value:@(dinSpacing)
                         range:NSMakeRange(0, [myString length])];

Solution

  • You can set character spacing for segment control as in the code below. You are doing it correctly, just add NSKernAttributeName as the key with a number value you are doing for the button, for example.

    [self.aSegMentCntrl setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:@(5),NSKernAttributeName,[UIColor redColor],NSForegroundColorAttributeName,[UIFont fontWithName:@"Helvetica Neue" size:13],NSFontAttributeName ,nil] forState:UIControlStateSelected];
    

    Your dictionary version

    [self.aSegMentCntrl setTitleTextAttributes:@{ NSKernAttributeName:@(5),NSForegroundColorAttributeName: [UIColor whiteColor], NSFontAttributeName: [UIFont fontWithName:@"Helvetica Neue" size:13]} forState:UIControlStateSelected];