1

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

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)
}

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

4

1 回答 1

6

Solved. iOS 14 expects attribute ID instead of its name ("Weight").

So, attributeDict should look like this:

var attributesDict = [NSNumber: Any]()
attributesDict[NSNumber(value: 2003265652)] = weight

Attribute ID can be obtained as follows:

let variationAxes = (CTFontCopyVariationAxes(ctFont)! as Array)
于 2020-12-12T20:34:50.500 回答