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:
I'd like it to look like this:
How can this be achieved?
"Short answer: you can't. To change the spacing between lines of text, you will have to subclass UILabel and roll your own drawTextInRect, or create multiple labels." This is a really old answer, and other have already addded the new and better way to handle this..
Kerning adjusts the spacing between any two letters while tracking affects spacing for more than two letters.
Change Font And Size Of UILabel In Storyboard To change the font or the size of a UILabel in a Storyboard or . XIB file, open it in the interface builder. Select the label and then open up the Attribute Inspector (CMD + Option + 5). Select the button on the font box and then you can change your text size or font.
The two modifiers are tracking() and kerning() : both add spacing between letters, but tracking will pull apart ligatures whereas kerning will not, and kerning will leave some trailing whitespace whereas tracking will not.
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];
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 } } }
On swift implementation looks like
let text = "TIPS, ARTICLES & BEST OFFERS"
label.attributedText = NSAttributedString(string: text, attributes: [.kern: 3.12])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With