Is there anyway to change the character spacing (track) on UILabel text using Interface Builder? If not, is there a way to do it programmatically on an existing UILabel that was already created with attributed text?
"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.. Please see the up to date answers provided below.
If you have created an UILabel programmatically, replace the UILabel class with the PaddingLabel and add the padding: // Init Label let label = PaddingLabel() label. backgroundColor = . black label.
Kerning defines the offset, in points, that a text view should shift characters from the default spacing. Use positive kerning to widen the spacing between characters. Use negative kerning to tighten the spacing between characters.
I know it's not an Interface Builder solution, but you can create a UILabel
extension and then add spacing to any UILabel
you want:
extension UILabel { func addCharacterSpacing(kernValue: Double = 1.15) { guard let text = text, !text.isEmpty else { return } let string = NSMutableAttributedString(string: text) string.addAttribute(NSAttributedString.Key.kern, value: kernValue, range: NSRange(location: 0, length: string.length - 1)) attributedText = string } }
Consider changing the default kernValue
from 1.15
to something that works better with your design.
When implementing always add character spacing after setting the text value:
myLabel.text = "We used to be so close" myLabel.addCharacterSpacing()
If you plan to have different spacing at different places in the app, you can override the default kern value:
myLabelWithSpecialNeeds.addCharacterSpacing(kernValue: 1.3)
This solution overrides any other attributes you might have on your UILabel
's attributedText
.
Ended up using this for now to get existing attributed text and modify to add character spacing:
let attributedString = discoveryTitle.attributedText as NSMutableAttributedString attributedString.addAttribute(NSKernAttributeName, value: 1.0, range: NSMakeRange(0, attributedString.length)) discoveryTitle.attributedText = attributedString
Swift 3:
let attributedString = NSMutableAttributedString(string: discoveryTitle.text) attributedString.addAttribute(NSKernAttributeName, value: CGFloat(1.0), range: NSRange(location: 0, length: attributedString.length)) discoveryTitle.attributedText = attributedString
Using NSRange instead of NSMakeRange works in Swift 3.
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