iOS 14 中的可变字体

RPl*_*lay 0 ios swift uifontdescriptor ios14 variable-fonts

以下代码允许创建具有不同权重的字体。

func makeFont(weight: CGFloat, size: CGFloat) -> UIFont {
    var attributesDict = [String: Any]()
    attributesDict["Weight"] = weight
    /* Rubik-Light - is a variable font */
    let fontDescriptor = UIFontDescriptor(
        fontAttributes: [
            UIFontDescriptor.AttributeName.name : "Rubik-Light",
            kCTFontVariationAttribute as UIFontDescriptor.AttributeName : attributesDict
        ]
    )
    return UIFont(descriptor: fontDescriptor, size: size)
}
Run Code Online (Sandbox Code Playgroud)

它在 ios 13 及更低版本上运行良好,但在 iOS 14 上不起作用。有什么解决方案吗?

RPl*_*lay 5

解决了。iOS 14 需要属性 ID 而不是其名称(“重量”)。

所以,attributeDict 应该是这样的:

var attributesDict = [NSNumber: Any]()
attributesDict[NSNumber(value: 2003265652)] = weight
Run Code Online (Sandbox Code Playgroud)

可以通过以下方式获取属性ID:

let variationAxes = (CTFontCopyVariationAxes(ctFont)! as Array)
Run Code Online (Sandbox Code Playgroud)

  • 感谢您发布您的解决方案。顺便说一句,这个数字只是“wght”(注册的 OpenType 轴)的四个 ASCII 字符,解释为 UInt32 (0x77676874) (4认同)