iOS 9中的At WWDC 2015, there was a session about the new “San Francisco” system font。默认情况下,当与iOS 9 SDK链接时,它使用比例数字渲染而不是等宽数字。 NSFont上有一个方便的初始化程序,名为NSFont.monospacedDigitsSystemFontOfSize(mySize weight:)
,可用于显式启用等宽数字显示。
但是我在UIKit
上找不到UIFont
相当于此。
方便的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
}
}
使用@IBOutlet
属性:
@IBOutlet private var timeLabel: UILabel? {
didSet {
timeLabel.font = timeLabel.font.monospacedDigitFont
}
}
GitHub的最新版本。
从iOS 9开始,这在UIFont
中可用:
+ (UIFont *)monospacedDigitSystemFontOfSize:(CGFloat)fontSize weight:(CGFloat)weight NS_AVAILABLE_IOS(9_0);
例如:
[UIFont monospacedDigitSystemFontOfSize:42.0 weight:UIFontWeightMedium];
或者在Swift中:
UIFont.monospacedDigitSystemFont(ofSize: 42.0, weight: UIFontWeightMedium)
接受的解决方案效果很好,但是在编译器优化设置为快速(发布版本的默认设置)时崩溃了。重写了这样的代码,现在它没有:
extension UIFont
{
var monospacedDigitFont: UIFont
{
return UIFont(descriptor: fontDescriptor().fontDescriptorByAddingAttributes([UIFontDescriptorFeatureSettingsAttribute: [[UIFontFeatureTypeIdentifierKey: kNumberSpacingType, UIFontFeatureSelectorIdentifierKey: kMonospacedNumbersSelector]]]), size: 0)
}
}
在Swift 4中有相当多的重命名,所以属性现在看起来像这样:
let fontDescriptorAttributes = [
UIFontDescriptor.AttributeName.featureSettings: [
[
UIFontDescriptor.FeatureKey.featureIdentifier: kNumberSpacingType,
UIFontDescriptor.FeatureKey.typeIdentifier: kMonospacedNumbersSelector
]
]
]
注意:当前接受的答案中的方法已经在Xcode 7.3(Swift 2.2)中开始崩溃,仅在发布版本中。消除中间monospacedDigitFontDescriptor
扩展变量修复了这个问题。
extension UIFont {
var monospacedDigitFont: UIFont {
let fontDescriptorFeatureSettings = [[UIFontFeatureTypeIdentifierKey: kNumberSpacingType, UIFontFeatureSelectorIdentifierKey: kMonospacedNumbersSelector]]
let fontDescriptorAttributes = [UIFontDescriptorFeatureSettingsAttribute: fontDescriptorFeatureSettings]
let oldFontDescriptor = fontDescriptor()
let newFontDescriptor = oldFontDescriptor.fontDescriptorByAddingAttributes(fontDescriptorAttributes)
return UIFont(descriptor: newFontDescriptor, size: 0)
}
}
检查iOS版本的@Rudolf Adamkovic代码的一点改进版本:
var monospacedDigitFont: UIFont {
if #available(iOS 9, *) {
let oldFontDescriptor = fontDescriptor()
let newFontDescriptor = oldFontDescriptor.monospacedDigitFontDescriptor
return UIFont(descriptor: newFontDescriptor, size: 0)
} else {
return self
}
}
或者,只需使用Helvetica。它仍然具有等宽数字,并且可以追溯到旧的iOS版本。