如何在iOS 9上的UILabel中获取等宽数字

Sam*_*ert 28 uilabel uifont monospace ios ios9

在WWDC 2015上,有一个关于 iOS 9中新"旧金山"系统字体的会话.默认情况下,当与iOS 9 SDK链接时,它使用比例数字渲染而不是等宽数字.在NSFont上有一个方便的初始化程序NSFont.monospacedDigitsSystemFontOfSize(mySize weight:),可用于显式启用等宽数字显示.

但是,我无法找到UIKit相应的UIFont.

Ric*_*tos 48

UIFont从iOS 9开始提供此功能:

+ (UIFont *)monospacedDigitSystemFontOfSize:(CGFloat)fontSize weight:(CGFloat)weight NS_AVAILABLE_IOS(9_0);
Run Code Online (Sandbox Code Playgroud)

例如:

[UIFont monospacedDigitSystemFontOfSize:42.0 weight:UIFontWeightMedium];
Run Code Online (Sandbox Code Playgroud)

或者在Swift中:

UIFont.monospacedDigitSystemFont(ofSize: 42.0, weight: UIFontWeightMedium)
Run Code Online (Sandbox Code Playgroud)

  • 这很好用,但它只适用于系统字体. (2认同)
  • @RudolfAdamkovic这是对的.等宽数字是系统字体(旧金山)的特征,尤其不是UIFont普遍提供的. (2认同)

Rud*_*vič 42

方便的UIFont扩展:

extension UIFont {
    var monospacedDigitFont: UIFont {
        let newFontDescriptor = fontDescriptor.monospacedDigitFontDescriptor
        return UIFont(descriptor: newFontDescriptor, size: 0)
    }
}

private extension UIFontDescriptor {
    var monospacedDigitFontDescriptor: UIFontDescriptor {
        let fontDescriptorFeatureSettings = [[UIFontDescriptor.FeatureKey.featureIdentifier: kNumberSpacingType,
                                              UIFontDescriptor.FeatureKey.typeIdentifier: kMonospacedNumbersSelector]]
        let fontDescriptorAttributes = [UIFontDescriptor.AttributeName.featureSettings: fontDescriptorFeatureSettings]
        let fontDescriptor = self.addingAttributes(fontDescriptorAttributes)
        return fontDescriptor
    }
}
Run Code Online (Sandbox Code Playgroud)

使用@IBOutlet属性:

@IBOutlet private var timeLabel: UILabel? {
    didSet {
        timeLabel.font = timeLabel.font.monospacedDigitFont
    }
}
Run Code Online (Sandbox Code Playgroud)

GitHub上的最新版本.

  • 谢谢@SamuelMellert.此信息应添加到答案中.我正在使用Rudolf的代码,它在我今天升级到Xcode 7.3之后就破了.调试非常困难; 它只会在构建发布时崩溃. (5认同)
  • 这已得到Xcode 7 beta 4的修复.UIFont现在具有与NSFont相同的monospacedDigitsSystemFontOfSize:weight:方法. (4认同)
  • 值得注意的是,所以人们不要用头撞墙,这不一定适用于任意字体。如果字体没有等宽数字支持,那么添加的特征属性将不会产生任何影响。 (2认同)

Chu*_*ris 5

接受的解决方案效果很好,但是在编译器优化设置为快速(发布版本的默认设置)时崩溃了.重写了这样的代码,现在它没有:

extension UIFont
{
    var monospacedDigitFont: UIFont
    {
        return UIFont(descriptor: fontDescriptor().fontDescriptorByAddingAttributes([UIFontDescriptorFeatureSettingsAttribute: [[UIFontFeatureTypeIdentifierKey: kNumberSpacingType, UIFontFeatureSelectorIdentifierKey: kMonospacedNumbersSelector]]]), size: 0)
    }
}
Run Code Online (Sandbox Code Playgroud)


sam*_*ize 5

在Swift 4中有相当多的重命名,所以属性现在看起来像这样:

    let fontDescriptorAttributes = [
        UIFontDescriptor.AttributeName.featureSettings: [
            [
                UIFontDescriptor.FeatureKey.featureIdentifier: kNumberSpacingType,
                UIFontDescriptor.FeatureKey.typeIdentifier: kMonospacedNumbersSelector
            ]
        ]
    ]
Run Code Online (Sandbox Code Playgroud)