我有以下代码:
[[cancelButton titleLabel] setFont:[UIFont fontWithName:@"ProximaNova-Regular" size:15]];
我该如何设置字母间距?
我有以下代码:
[[cancelButton titleLabel] setFont:[UIFont fontWithName:@"ProximaNova-Regular" size:15]];
我该如何设置字母间距?
在摘要中,您无法更改字母间距,这意味着在iOS 5及以下版本中根本无法更改。
从iOS 6开始,您可以将带属性的字符串推送到UILabel
而不是普通字符串。推送带属性的字符串的过程与推送普通字符串的过程略有不同-字体、文本颜色和许多其他属性都设置在字符串上而不是标签上。原因是带属性的字符串允许为字符串的不同区域设置不同的属性。因此,您可以设置组合多个字体、文本颜色等的字符串。
支持的Core Text属性之一是kCTKernAttributeName
,自iOS 6以来,通过UIKit添加NSKernAttributeName
更容易利用。您可以使用字距调整字形的水平间距。
在iOS 5及更早版本中,您曾经不得不在Core Foundation C样式对象和Objective-C UIKit对象之间进行大量的心理跳跃。自第6版以来,这已不再需要。但是,如果您在互联网上搜索,事情在6下变得更加容易-如果您看到许多__bridge
转换和手动CFRelease
,那么您可能正在查看旧代码。
假设您目前拥有以下内容:
UILabel *label = [cancelButton titleLabel];
UIFont *font = <whatever>;
UIColor *textColour = <whatever>;
NSString *string = <whatever>;
label.text = string;
label.font = font;
label.textColor = textColour;
你应该像这样做:
NSAttributedString *attributedString =
[[NSAttributedString alloc]
initWithString:string
attributes:
@{
NSFontAttributeName : font,
NSForegroundColorAttributeName : textColour
}];
label.attributedText = attributedString;
在您的情况下,为了调整整体字符间距,您需要添加:NSAttributedString *attributedString =
[[NSAttributedString alloc]
initWithString:string
attributes:
@{
NSFontAttributeName : font,
NSForegroundColorAttributeName : textColour,
NSKernAttributeName : @(-1.3f)
}];
label.attributedText = attributedString;
或者您想应用的任何字距值。请参见NSAttributedString UIKit Additions Reference底部的各种常量,了解您可以应用的其他属性以及它们首次在哪个iOS版本上可用。
后来追加:虽然仍然是您会遇到的最不擅长使用Swift的人之一,但我认为这是Swift中的等效内容:
button.titleLabel?.attributedText =
NSAttributedString(
string: string,
attributes:
[
NSFontAttributeName: font,
NSForegroundColorAttributeName: textColour,
NSKernAttributeName: -1.3
])
NSAttributedString *cancelButtonAttributedString = [[NSAttributedString alloc]
initWithString:@"Hello"
attributes:
@{
NSKernAttributeName: @(1.5)
}];
[cancelButton setAttributedTitle:cancelButtonAttributedString forState:UIControlStateNormal];
这只是对上述问题的简单回答。
NSParagraphStyle
有一个可以设置的lineSpacing
属性。请参考文档。需要注意的是,它设置的是行间距,这也是“行距”一词最初的定义:字体之间的间距,通常是通过铅字来实现的。我曾经学过,行距等于字体大小加上行间距。 - davextreme