How do I change the letter spacing in a UILabel?

Ben Thomas picture Ben Thomas · Jun 7, 2016 · Viewed 25.1k times · Source

I want to change the spacing between digits in a UIKit UILabel so that it is equal.

With standard spacing, the label looks like this:

label with uneven character spacing

I'd like it to look like this:

label with even character spacing

How can this be achieved?

Answer

J2K picture J2K · Jun 8, 2016

You can use the NSKernAttributeName attribute on an attributed string:

UILabel *label = [UILabel new];

NSMutableAttributedString *text = [[NSMutableAttributedString alloc] 
                                   initWithString:@"127"];

// The value paramenter defines your spacing amount, and range is 
// the range of characters in your string the spacing will apply to. 
// Here we want it to apply to the whole string so we take it from 0 to text.length.
[text addAttribute:NSKernAttributeName 
             value:@-0.5 
             range:NSMakeRange(0, text.length)];

[label setAttributedText:text];