How do I change the letter spacing in a UILabel?
The easiest way is to create a custom UILabel class and set the letter spacing from Storyboard.
open class CustomLabel : UILabel {
@IBInspectable open var characterSpacing:CGFloat = 1 {
didSet {
let attributedString = NSMutableAttributedString(string: self.text!)
attributedString.addAttribute(NSKernAttributeName, value: self.characterSpacing, range: NSRange(location: 0, length: attributedString.length))
self.attributedText = attributedString
}
}
}
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];