ios 如何更改 UILabel 中的字母间距?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37689785/
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 do I change the letter spacing in a UILabel?
提问by Ben Thomas
回答by J2K
You can use the NSKernAttributeName
attribute on an attributed string:
您可以NSKernAttributeName
在属性字符串上使用该属性:
UILabel *label = [UILabel new];
NSMutableAttributedString *text = [[NSMutableAttributedString alloc]
initWithString:@"127"];
// The value paramenter defines your spacing amount, and range is
// the range of characters in your string the spacing will apply to.
// Here we want it to apply to the whole string so we take it from 0 to text.length.
[text addAttribute:NSKernAttributeName
value:@-0.5
range:NSMakeRange(0, text.length)];
[label setAttributedText:text];
回答by miOS
The easiest way is to create a custom UILabel class and set the letter spacing from Storyboard.
最简单的方法是创建一个自定义 UILabel 类并从 Storyboard 设置字母间距。
open class CustomLabel : UILabel {
@IBInspectable open var characterSpacing:CGFloat = 1 {
didSet {
let attributedString = NSMutableAttributedString(string: self.text!)
attributedString.addAttribute(NSKernAttributeName, value: self.characterSpacing, range: NSRange(location: 0, length: attributedString.length))
self.attributedText = attributedString
}
}
}
回答by Joel Nieman
You can use an NSAttributedString and play with the NSKernAttributeName attribute. The default value for this is 0 so you will want to set it to a negative number.
您可以使用 NSAttributedString 并使用 NSKernAttributeName 属性。默认值为 0,因此您需要将其设置为负数。
in Obj-C you can do something like this:
在 Obj-C 中,您可以执行以下操作:
NSMutableAttributedString* attrStr = [[NSMutableAttributedString alloc]initWithString: @"Test test test test "];
[attrStr addAttribute:NSKernAttributeName value:@(4.0) range:NSMakeRange(0, attrStr.length)];
label.attributedText = attrStr;
in Swift you could do something like this:
在 Swift 中,您可以执行以下操作:
let myTitle = "my title"
let titleLabel = UILabel()
let attributes: NSDictionary = [
NSFontAttributeName:UIFont(name: "FONT_NAME", size: TEXT_SIZE),
NSKernAttributeName:CGFloat(2.0)
]
let attributedTitle = NSAttributedString(string: myTitle, attributes:attributes as? [String : AnyObject])
titleLabel.attributedText = attributedTitle
回答by Pomme2Poule
I've taken the answer from @J2K and translated it into a Swift 4.2extension.
我从@J2K 那里得到了答案,并将其翻译成Swift 4.2扩展。
/// Set the text of the label but altering the kerning so that you can control the space between each characters.
///
/// - Parameters:
/// - text: New content of the label
/// - kerning: Set a value between 0 and 1 to lower the space between characters. Above 0, spacing will be increased. 0 disables kerning.
extension UILabel {
func set(text: String, withKerning kerning: CGFloat) {
let attributedString = NSMutableAttributedString(string: text)
// The value parameter defines your spacing amount, and range is
// the range of characters in your string the spacing will apply to.
// Here we want it to apply to the whole string so we take it from 0 to text.count.
attributedString.addAttribute(NSAttributedString.Key.kern, value: kerning, range: NSMakeRange(0, text.count))
attributedText = attributedString
}
}
回答by LLIAJLbHOu
回答by jn-se
The NSKernAttributeNamecan be used.
该NSKernAttributeName可以使用。
But in correction to the other answers: Do not apply to the full text length, but (text.length - 1).
但更正其他答案:不适用于全文长度,但(text.length - 1)。
The negative or positive spacing is added to the letter and this is not required for the last one. Assume you would add a positive spacing it would end up in a spacing after the last letter. A centered string would not appear to be centered anymore. The same applies for negative spacing.
将负或正间距添加到字母中,最后一个不需要。假设您要添加一个正间距,它会在最后一个字母之后的间距中结束。居中的字符串似乎不再居中。这同样适用于负间距。
NSString *text = @"Sample Text";
UILabel *label = [UILabel new]
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString: text];
[attributedString addAttribute:NSKernAttributeName value:[NSNumber numberWithDouble:-1.0] range:NSMakeRange(0, text.length-1)];
[label setAttributedTitle:attributedString forState:UIControlStateNormal];
Applied to full text length.
应用于全文长度。
回答by Alexander Volkov
If you want to apply the letter spacing attribute to all UILabels in Interface Builder without modifying anything (for particular font):
如果要将字母间距属性应用于 Interface Builder 中的所有 UILabels 而不修改任何内容(对于特定字体):
Swift 4:
斯威夫特 4:
/**
* Applies letter spacing to selected fonts in UILabels from IB.
*
* - author Alexander Volkov
* - version 1.0
*/
extension UILabel {
/// Applies letter spacing
open override func awakeFromNib() {
super.awakeFromNib()
applyLetterSpacing()
}
/// Applies letter spacing
///
/// - Parameter aDecoder: the decoder
/// - Returns: UILabel instance
open override func awakeAfter(using aDecoder: NSCoder) -> Any? {
let label = super.awakeAfter(using: aDecoder)
self.applyLetterSpacing()
return label
}
/// Applies letter spacing
func applyLetterSpacing() {
if font.fontName.contains("Oswald", caseSensitive: false) {
let characterSpacing: CGFloat = 1
let string = NSMutableAttributedString(string: self.text!)
string.addAttribute(.kern, value: characterSpacing, range: NSRange(location: 0, length: string.length - 1))
self.attributedText = string
}
}
}
回答by emotality
NSString *myString = @"127";
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:myString];
float letterSpacing = -1.50f; // change spacing here
[attributedString addAttribute:NSKernAttributeName value:@(letterSpacing) range:NSMakeRange(0, [myString length])];
[myLabel setAttributedText:attributedString];
Also see this for more info and results: http://www.devsign.co/notes/tracking-and-character-spacing
另请参阅此以获取更多信息和结果:http: //www.devsign.co/notes/tracking-and-character-spacing
回答by Umair
Try this. It will add the character spacing you assign, either you set simple text or attributed text. https://stackoverflow.com/a/49929848/4559803
尝试这个。它将添加您分配的字符间距,您可以设置简单文本或属性文本。https://stackoverflow.com/a/49929848/4559803
回答by themenace
I found this to be the best solution. It includes also UIButton, applies attributes that may have been set in interface builder and adapts to different fonts:
我发现这是最好的解决方案。它还包括 UIButton,应用可能已在界面构建器中设置的属性并适应不同的字体:
extension UILabel {
open override func awakeFromNib() {
super.awakeFromNib()
applyLetterSpacing()
}
func applyLetterSpacing() {
// return if empty text
if((text ?? "").isEmpty) {
return
}
// default spacing
var spacing = 1
if(font.familyName == "Source Serif Pro") {
// custom spacing for different font
spacing = 2
}
var attributes = attributedText?.attributes(at: 0, effectiveRange: nil) ?? [:]
attributes[.kern] = spacing
attributedText = NSAttributedString(string: text ?? "", attributes: attributes)
}
}
and for Buttons
和按钮
extension UIButton {
open override func awakeFromNib() {
super.awakeFromNib()
applyLetterSpacing()
}
func applyLetterSpacing() {
if((title(for: .normal) ?? "").isEmpty) {
return
}
var attributes = attributedTitle(for: .normal)?.attributes(at: 0, effectiveRange: nil) ?? [:]
attributes[.kern] = 1
attributes[.foregroundColor] = titleColor(for: .normal)
setAttributedTitle(NSAttributedString(string: title(for: .normal) ?? "", attributes: attributes), for: .normal)
}
}