简体   繁体   English

获取 iOS 14 中的 Font.Weight

[英]Get Font.Weight in iOS 14

In iOS 13 and low I got Font.Weight using this extension for UIFont在 iOS 13 和低我得到 Font.Weight 使用 UIFont 这个扩展

var weight: UIFont.Weight {
    guard let traits = fontDescriptor.object(forKey: .traits) as? [UIFontDescriptor.TraitKey: Any], let weightValue = traits[.weight] as? CGFloat else { return .regular }
    let weight = UIFont.Weight(rawValue: weightValue)
    return weight
}

But since iOS 14 weightValue is wrong.但是由于 iOS 14 weightValue 是错误的。 For example:例如:

let font = UIFont(name: "AvenirNext-Bold", size: 21)
print(font?.weight.rawValue)
print(font?.weight == .bold)

iOS 14 - 0.40000000000000002 false iOS 14 - 0.40000000000000002 假

iOS 13 - 0.40000000596046448 true iOS 13 - 0.40000000596046448 真

Anybody faced with it?有人遇到过吗?

This is not a bug.这不是错误。 It is in fact expected to be inaccurate after a high number of decimal places (16 in this case).事实上,在大量小数位(在本例中为 16 个)之后,它预计会不准确。 Floats are calculated via the IEEE 754 standard for Single-Precision Floating-Point arithmetic.浮点数通过 IEEE 754 单精度浮点算法标准计算。 The original standard was only accurate up to 7 decimal places for integers between 4 and 6, but this has iteratively improved since the original, for example in 2019 and 2020 (see here for details).对于 4 到 6 之间的整数,原始标准仅精确到小数点后 7 位,但自原始标准以来,这一标准得到了迭代改进,例如在 2019 年和 2020 年(详见此处)。

What you see is probably the effect of conditional casting.你看到的可能是条件转换的效果。 The conversion from Float to CGFloat loses precision.FloatCGFloat的转换会丢失精度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM