简体   繁体   中英

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.

You can set the title via code passing the title string with some blank spacing ("E xample"), 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.

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
}

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM