Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change letter spacing in Swift?

I'd like to change the letter spacing in the title of my navigation bar but I've had no success so far.

Thanks in advance.

like image 449
user1681004 Avatar asked Oct 11 '14 22:10

user1681004


2 Answers

A cool extension for UILabel:

extension UILabel{
func setCharacterSpacing(_ spacing: CGFloat){
    let attributedStr = NSMutableAttributedString(string: self.text ?? "")
    attributedStr.addAttribute(NSAttributedString.Key.kern, value: spacing, range: NSMakeRange(0, attributedStr.length))
    self.attributedText = attributedStr
 }
}

Usage:

label.setCharacterSpacing(4)
like image 92
Quintus_2 Avatar answered Oct 25 '22 18:10

Quintus_2


You can set the title via code passing the title string with some blank spacing ("E x a m p l e"), or with a tab (\t) or via code like this:

 let attributedString = NSMutableAttributedString(string: "Example")
 attributedString.addAttribute(NSKernAttributeName, value:   CGFloat(1.4), range: NSRange(location: 0, length: 9))

Then you assign attributedString to your title.

like image 39
Trainee Programmer Avatar answered Oct 25 '22 18:10

Trainee Programmer