为正文样式启用 iOS 系统字体中的排版功能

Enabling typographic features in iOS system font for body text style

我想通过启用它支持的 OpenType 功能来修改 San Francisco 字体,例如 one storey a or opened four and six。此设置应仅适用于 正文文本样式

文本样式在 Storyboard 属性检查器中设置,不在代码中

由于某种原因,下面的代码不起作用:

let bodyFontDescriptor = UIFontDescriptor.preferredFontDescriptor(withTextStyle: .body)
// This isn’t working either: let bodyFontDescriptor = UIFont.preferredFont(forTextStyle: .body).fontDescriptor
let oneStoreyAFontDescriptor = bodyFontDescriptor.addingAttributes(
    [
        UIFontDescriptorFeatureSettingsAttribute:
        [
            [
                UIFontFeatureTypeIdentifierKey: kStylisticAlternativesType,
                UIFontFeatureSelectorIdentifierKey: kStylisticAltSevenOnSelector
            ]
        ]
    ]
)
textView.font = UIFont(descriptor: oneStoreyAFontDescriptor, size: 0.0)

我做错了什么?一般来说,这是正确的方法吗?

看来您需要尝试使用选择器。结合 SixSeven 替代方案后,以下代码开始工作:

let six = [UIFontFeatureTypeIdentifierKey: kStylisticAlternativesType,
                       UIFontFeatureSelectorIdentifierKey: kStylisticAltSixOnSelector]
let seven = [UIFontFeatureTypeIdentifierKey: kStylisticAlternativesType,
                         UIFontFeatureSelectorIdentifierKey: kStylisticAltSevenOnSelector]
let descriptor = UIFontDescriptor.preferredFontDescriptor(withTextStyle: .body).addingAttributes([UIFontDescriptorFeatureSettingsAttribute: [six, seven]])
let font = UIFont(descriptor: descriptor, size: 0.0)
label.font = font

我找到了无法将字体属性应用于文本样式的原因。我在视图的 属性检查器 中检查了 Dynamic Type Automatically Adjusts Font 的复选标记。这在某种程度上干扰了代码中设置的字体功能的激活。