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)
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上的最新版本.
接受的解决方案效果很好,但是在编译器优化设置为快速(发布版本的默认设置)时崩溃了.重写了这样的代码,现在它没有:
extension UIFont
{
var monospacedDigitFont: UIFont
{
return UIFont(descriptor: fontDescriptor().fontDescriptorByAddingAttributes([UIFontDescriptorFeatureSettingsAttribute: [[UIFontFeatureTypeIdentifierKey: kNumberSpacingType, UIFontFeatureSelectorIdentifierKey: kMonospacedNumbersSelector]]]), size: 0)
}
}
Run Code Online (Sandbox Code Playgroud)
在Swift 4中有相当多的重命名,所以属性现在看起来像这样:
let fontDescriptorAttributes = [
UIFontDescriptor.AttributeName.featureSettings: [
[
UIFontDescriptor.FeatureKey.featureIdentifier: kNumberSpacingType,
UIFontDescriptor.FeatureKey.typeIdentifier: kMonospacedNumbersSelector
]
]
]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11643 次 |
| 最近记录: |