Search code examples
iosswiftuilabelinterface-builder

Change character spacing on UILabel within Interface Builder


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?


Solution

  • 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.