How to increase the character spacing in UILabel

Viewed 32956

I am creating an app in >=iOS6. And I want to change the character spacing in UILabel. I have added the custom font "FUTURABT HEAVY" in my app but the Character are too close to eachother.

I have find the good code here to increase the character spacing. But if i tried to change it than my text became left- align in stead of center.

Please help me with this situation.

6 Answers

Here the code for Swift 5 with a handy extension :

extension UILabel {
    func addCharactersSpacing(spacing: CGFloat, txt: String) {
        let attributedString = NSMutableAttributedString(string: txt)
        attributedString.addAttribute(NSAttributedString.Key.kern, value: spacing, range: NSRange(location: 0, length: txt.count))
        self.attributedText = attributedString
    }
}

Swift 4.2 with UILabel extension and @IBInspectable

extension UILabel {
@IBInspectable var letterSpacing: CGFloat {
    get {
        var range:NSRange = NSMakeRange(0, self.text?.count ?? 0)
        let nr = self.attributedText?.attribute(NSAttributedString.Key.kern, at: 0, effectiveRange: &range) as! NSNumber
        return CGFloat(truncating: nr)
    }

    set {
        let range:NSRange = NSMakeRange(0, self.text?.count ?? 0)

        let attributedString = NSMutableAttributedString(string: self.text ?? "")
        attributedString.addAttribute(NSAttributedString.Key.kern, value: newValue, range: range)
        self.attributedText = attributedString
    }
}

}

Related