17

我有以下代码:

[[cancelButton titleLabel] setFont:[UIFont fontWithName:@"ProximaNova-Regular" size:15]];

我将如何设置字母间距?

4

3 回答 3

54

不能更改摘要中的字母间距,也就是说在iOS 5 及以下版本下根本无法更改。

从 iOS 6 开始,您可以将属性字符串而不是普通字符串推送到UILabel. 推送属性字符串的过程与推送普通字符串的过程略有不同——字体、文本颜色和一堆其他属性都设置在字符串而不是标签上。原因是属性字符串允许为字符串的不同区域设置不同的属性。因此,您可以设置一个组合多种字体、文本颜色等的字符串。

支持的核心文本属性之一是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 上可用。

很久以后的附录:虽然仍然是你会遇到的最少的 Swifty 人之一,但我认为这是 Swift 中的等价物:

button.titleLabel?.attributedText =
    NSAttributedString(
        string: string,
        attributes:
        [
            NSFontAttributeName: font,
            NSForegroundColorAttributeName: textColour,
            NSKernAttributeName: -1.3
        ])
于 2013-10-11T21:27:38.200 回答
2
    NSAttributedString *cancelButtonAttributedString = [[NSAttributedString alloc]
                                           initWithString:@"Hello"
                                           attributes:
                                           @{
                                             NSKernAttributeName: @(1.5)
                                             }];
    [cancelButton setAttributedTitle:cancelButtonAttributedString forState:UIControlStateNormal];

这只是上述问题的简单答案

于 2018-01-18T08:30:32.077 回答
1

支持的核心文本属性之一是 kCTKernAttributeName,从 iOS 6 开始,通过 UIKit 添加 NSKernAttributeName 更容易利用它。您可以使用字距调整字形的水平间距。

字距调整是两个唯一字母之间的空间调整。字距在不同的字符对之间变化。例如,像“AVA”这样的组合在字符之间的字距调整与像“VVV”这样的组合不同

通过使用 NSKernAttributeName,您实际上覆盖了内置在字体文件中的自定义空间调整,将所有不同的字符对紧缩值设置为相同的数字,从而破坏了最佳紧缩。当应用于整个文本字符串时,少量的字距调整会更明显。然而,高字距值可能会将字母推得足够远,以至于差的间距不会那么明显。

您正在寻找的是跟踪(又名字母间距),它是给定文本块中所有字母之间的间距。不幸的是,iOS 似乎不允许您控制该属性。

于 2014-12-11T01:31:19.893 回答