Dav*_*542 16 objective-c uilabel uifont ios
我有以下代码:
[[cancelButton titleLabel] setFont:[UIFont fontWithName:@"ProximaNova-Regular" size:15]];
Run Code Online (Sandbox Code Playgroud)
我如何设置字母间距?
Tom*_*mmy 53
您无法在摘要中更改字母间距,这意味着您无法在iOS 5及更低版本下更改它.
从iOS 6开始,您可以将属性字符串而不是香草字符串推送到a 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;
Run Code Online (Sandbox Code Playgroud)
你会做更像的事情:
NSAttributedString *attributedString =
[[NSAttributedString alloc]
initWithString:string
attributes:
@{
NSFontAttributeName : font,
NSForegroundColorAttributeName : textColour
}];
label.attributedText = attributedString;
Run Code Online (Sandbox Code Playgroud)
在您的情况下,还要调整您添加的整体字距:
NSAttributedString *attributedString =
[[NSAttributedString alloc]
initWithString:string
attributes:
@{
NSFontAttributeName : font,
NSForegroundColorAttributeName : textColour,
NSKernAttributeName : @(-1.3f)
}];
label.attributedText = attributedString;
Run Code Online (Sandbox Code Playgroud)
或者您想要应用的任何字距调整值.请参阅NSAttributedString UIKit Additions Reference底部的各种常量,了解您可以应用的各种其他属性以及它们最初可用的iOS版本.
很久以后的补遗:虽然仍然是你遇到过的人数最少的人之一,但我认为这与Swift相当:
button.titleLabel?.attributedText =
NSAttributedString(
string: string,
attributes:
[
NSFontAttributeName: font,
NSForegroundColorAttributeName: textColour,
NSKernAttributeName: -1.3
])
Run Code Online (Sandbox Code Playgroud)