如何在iOS 9上的UILabel中获取等宽数字 [英] How to get monospaced numbers in UILabel on iOS 9
问题描述
在WWDC 2015上,有一个关于新旧金山系统字体的会话在iOS 9中。当与iOS 9 SDK链接时,它默认使用比例数字渲染而不是等宽数字。在NSFont上有一个方便的初始化程序,名为 NSFont.monospacedDigitsSystemFontOfSize(mySize weight:)
,可用于显式启用等宽数字显示。
At WWDC 2015, there was a session about the new "San Francisco" system font in iOS 9. It uses proportional number rendering instead of monospaced numbers by default when linked against the iOS 9 SDK. There is a convenient initializer on NSFont called NSFont.monospacedDigitsSystemFontOfSize(mySize weight:)
that can be used to explicitly enable monospaced number display.
但是我在 UIFont
上找不到 UIKit
的等价物。
However I couldn't find the UIKit
equivalent for this on UIFont
.
推荐答案
Handy UIFont
扩展名:
Handy UIFont
extension:
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上的UILabel中获取等宽数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!