Search code examples
iosuilabelspacing

How do I change the letter spacing in a UILabel?


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?


Solution

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