问题描述
在 iOS 13 及更低版本中,我使用 UIFont 的此扩展获得了 Font.Weight
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
}
但由于 iOS 14 weightValue 是错误的。 例如:
let font = UIFont(name: "AvenirNext-Bold",size: 21)
print(font?.weight.rawValue)
print(font?.weight == .bold)
iOS 14 - 0.40000000000000002 错误
iOS 13 - 0.40000000596046448 真
有人遇到过吗?
解决方法
这不是错误。事实上,在大量小数位(在本例中为 16)之后,预计会不准确。浮点数是通过 IEEE 754 单精度浮点算法标准计算的。对于 4 到 6 之间的整数,原始标准的准确度最高可达 7 decimal places,但自原始标准以来已得到迭代改进,例如在 2019 年和 2020 年(有关详细信息,请参阅 here)。
你看到的可能是条件转换的效果。从 Float
到 CGFloat
的转换失去了精度。