iOS14中的可变字体
以下代码允许创建具有不同权重的字体。
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 上不起作用。有什么解决方案吗?
回答
解决了。iOS 14 需要属性 ID 而不是其名称(“重量”)。
所以,attributeDict 应该是这样的:
var attributesDict = [NSNumber: Any]()
attributesDict[NSNumber(value: 2003265652)] = weight
可以通过以下方式获取属性ID:
let variationAxes = (CTFontCopyVariationAxes(ctFont)! as Array)