简体   繁体   English

如何在Swift中更改字母间距?

[英]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: 您可以通过以下方式设置标题:通过以一定的空格(“ E xample”)传递标题字符串的代码,或者使用制表符(\\ t)传递标题的代码,或者通过如下代码:

 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. 然后,将attributedString分配给标题。

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: 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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