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

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

不过,我无法在UIFont上find相应的UIKit

方便的UIFont扩展:

 extension UIFont { var monospacedDigitFont: UIFont { let oldFontDescriptor = fontDescriptor() let newFontDescriptor = oldFontDescriptor.monospacedDigitFontDescriptor return UIFont(descriptor: newFontDescriptor, size: 0) } } private extension UIFontDescriptor { var monospacedDigitFontDescriptor: UIFontDescriptor { let fontDescriptorFeatureSettings = [[UIFontFeatureTypeIdentifierKey: kNumberSpacingType, UIFontFeatureSelectorIdentifierKey: kMonospacedNumbersSelector]] let fontDescriptorAttributes = [UIFontDescriptorFeatureSettingsAttribute: fontDescriptorFeatureSettings] let fontDescriptor = self.fontDescriptorByAddingAttributes(fontDescriptorAttributes) return fontDescriptor } } 

使用@IBOutlet属性:

 @IBOutlet private var timeLabel: UILabel? { didSet { timeLabel.font = timeLabel.font.monospacedDigitFont } } 

GitHub上的最新版本。

从iOS 9开始,这个function现在可以在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) 

接受的解决scheme效果很好,但是编译器优化设置为Fast(发布版本的默认设置)时崩溃了。 重写这样的代码,现在它不:

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

注意:目前被接受的答案中的方法在Xcode 7.3(Swift 2.2)中已经开始崩溃,仅在Release版本中。 消除中间monospacedDigitFontDescriptor扩展variables可以解决问题。

 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) } } 

一个改进版本的@Rudolf Adamkovic代码,用于检查iOS版本:

 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版本。

Interesting Posts