xcode 如何在 Swift 中更改字母间距?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26320056/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to change letter spacing in Swift?
提问by user1681004
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.
提前致谢。
回答by Juan Villalvazo
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:
您可以通过传递带有一些空格(“E xampl e”)的标题字符串的代码或使用制表符(\ 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 分配给你的标题。
回答by Patel Jigar
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
}
回答by Quintus_2
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)