adjustsFontSizeToFitWidth 在 iOS 14 上无法与 NSMutableAttributedString 一起正常工作

adjustsFontSizeToFitWidth does not work properly with NSMutableAttributedString on iOS 14

我需要缩小文字大小以适应特定区域的宽度。文本包含一些不同的格式设置(主要是文本颜色)所以我使用 NSMutableAttributedString

然后我设置 adjustsFontSizeToFitWidth 以适应边界矩形。

testLabel.minimumScaleFactor = 0.1
testLabel.adjustsFontSizeToFitWidth = true
let attributedGreen = NSAttributedString(string: "GREEN", attributes: [NSAttributedString.Key.foregroundColor: UIColor.green])
let attributedYellow = NSAttributedString(string: "YELLOW", attributes: [NSAttributedString.Key.foregroundColor: UIColor.yellow])
let textCombination = NSMutableAttributedString()
textCombination.append(attributedGreen)
textCombination.append(attributedYellow)
textCombination.append(attributedGreen)
textCombination.append(attributedYellow)
testLabel.attributedText = textCombination

预期的结果是有一个完整的可见文本并重新缩放到正确的字体大小,但它没有发生并且文本被截断。

如果我不使用属性字符串,一切正常:

testLabel.minimumScaleFactor = 0.1
testLabel.adjustsFontSizeToFitWidth = true     
testLabel.text = "GREENYELLOWGREENYELLOW"

这是正确的做法吗?如何正确调整字体大小?

补充说明: 我刚刚在设备 运行 iOS 13(而不是 iOS 14)上测试了它,使用属性字符串重新缩放字体效果很好。

会不会是 iOS 14 的错误?有任何解决方法建议吗?

更新 2020/10/26:我刚刚使用 iOS 14.0.1 对其进行了测试,但问题仍然存在。

您可以通过 storyBoard/Interface Builder 或像这样以编程方式将标签的最小比例因子简单地设置为 0.5

Yourlabel.minimumScaleFactor = 0.5

这似乎是一个 iOS 14 错误 openradar.appspot.com/FB8699725 因此,为了正确修复,我们必须等待新的 iOS 版本,同时我应用以下 quick-and-dirty 解决方法:

testLabel.minimumScaleFactor = 0.1
testLabel.adjustsFontSizeToFitWidth = true

let attributedGreen = NSAttributedString(string: "GREEN", attributes: [NSAttributedString.Key.foregroundColor: UIColor.green])
let attributedYellow = NSAttributedString(string: "YELLOW", attributes: [NSAttributedString.Key.foregroundColor: UIColor.yellow])
let attributedWorkaroud = NSAttributedString(string: ".", attributes: [NSAttributedString.Key.foregroundColor: UIColor(red: 1, green: 1, blue: 1, alpha: 0)])
let textCombination = NSMutableAttributedString()
textCombination.append(attributedGreen)
textCombination.append(attributedYellow)
textCombination.append(attributedGreen)
textCombination.append(attributedYellow)
textCombination.append(attributedWorkaroud)
testLabel.attributedText = textCombination

我在字符串的末尾添加了一个透明点。 它会产生一点错位,但至少这个词是可读的。

更新 2020/12/17 已在 iOS 14.2

中修复