How to change letter spacing in Swift?

2019-05-03 10:00发布

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.

3条回答
男人必须洒脱
2楼-- · 2019-05-03 10:32

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)
查看更多
姐就是有狂的资本
3楼-- · 2019-05-03 10:39

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.

查看更多
戒情不戒烟
4楼-- · 2019-05-03 10:45

the bellow function works for me, hope this helps you too

func setCharacterSpacig(string:String) -> NSMutableAttributedString {

    let attributedStr = NSMutableAttributedString(string: string)
    attributedStr.addAttribute(NSKernAttributeName, value: 1.25, range: NSMakeRange(0, attributedStr.length))
    return attributedStr
}
查看更多
登录 后发表回答