我的 Xcode 7、iOS 9 目标项目中包含自定义字体。我想让字体变成等宽字体。我尝试了这个,但没有成功:
let originalFont = UIFont(name: "My Custom Font", size: 18)
let originalFontDescriptor = originalFont!.fontDescriptor()
let fontDescriptorFeatureSettings = [
[
UIFontFeatureTypeIdentifierKey: kNumberSpacingType,
UIFontFeatureSelectorIdentifierKey: kMonospacedNumbersSelector
]
]
let fontDescriptorAttributes = [UIFontDescriptorFeatureSettingsAttribute: fontDescriptorFeatureSettings]
let fontDescriptor = originalFontDescriptor.fontDescriptorByAddingAttributes(fontDescriptorAttributes)
let font = UIFont(descriptor: fontDescriptor, size: 0)
topLabel.font = font
无论有或没有上述代码,标签都会以正确的自定义字体显示。只是上面的代码没有做任何事情。
我的以下答案只是将现有字体的数字(而不是整个字体)设置为等宽字体(如果字体支持)
至少我在找到这个线程时正在寻找使数字等宽。所以我希望它能有所帮助,尽管它回答了另一个问题。
这工作得很好,在 Swift 5 和 iOS14+13 上测试过:
(只要“您的字体支持等宽数字功能”.)
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 = [[UIFontDescriptor.FeatureKey.featureIdentifier: kNumberSpacingType, UIFontDescriptor.FeatureKey.typeIdentifier: kMonospacedNumbersSelector]]
let fontDescriptorAttributes = [UIFontDescriptor.AttributeName.featureSettings: fontDescriptorFeatureSettings]
let fontDescriptor = self.addingAttributes(fontDescriptorAttributes)
return fontDescriptor
}
}
然后你可以在任何标签上使用它,如下所示:
/// Label with monospacing activated
myLabel.font = myLabel.font.monospacedDigitFont
/// Label with monospacing not activated (default is proportional spacing)
myLabel.font = myLabel.font
(来源:https://blog.usejournal.com/proportional-vs-monospaced-numbers-when-to-use-which-one-in-order-to-avoid-wiggling-labels-e31b1c83e4d0)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)