ios - adjustsFontSizeToFitWidth 在 iOS 14 上与 NSMutableAttributedString 无法正常工作

标签 ios swift uilabel nsattributedstring nsmutableattributedstring

我需要减小文本大小以适应特定区域的宽度。文本包含一些不同的格式设置(主要是文本颜色),所以我使用 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
enter image description here
预期的结果是有一个完整的可见文本并重新缩放到正确的字体大小,但它不会发生并且文本被截断。
如果我不使用属性字符串,一切正常:
testLabel.minimumScaleFactor = 0.1
testLabel.adjustsFontSizeToFitWidth = true     
testLabel.text = "GREENYELLOWGREENYELLOW"
enter image description here
这是正确的做法吗?如何正确重新缩放字体大小?
额外说明:
我刚刚在运行 iOS 13(而不是 iOS 14)的设备上对其进行了测试,并且使用属性字符串重新缩放字体工作正常。
enter image description here
这可能是 iOS 14 的错误吗?任何解决方法建议?
2020/10/26 更新:我刚刚使用 iOS 14.0.1 对其进行了测试,但问题仍然存在。

最佳答案

似乎是 iOS 14 的错误 openradar.appspot.com/FB8699725
因此,为了正确修复,我们必须等待新的 iOS 版本,同时我应用以下快速和肮脏的解决方法:

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 中修复

关于ios - adjustsFontSizeToFitWidth 在 iOS 14 上与 NSMutableAttributedString 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64483280/

相关文章:

ios - subview 位置不正确

iOS 自动更新订阅购买问题

iOS 透明 View Controller

ios - 如何将 DataResponse<Any> 转换为 DefaultDataResponse

ios - NSMutableAttributedString 如何放置 1 个大单词,然后放置 2 行

ios - 为什么需要覆盖 layoutSubviews

ios - 调用函数时无法隐藏 iOS 工具栏

swift - 使用 Swift,为什么按下一个 UIStepper 会影响两个步进器?

ios - 简单地改变 UILabel 中的颜色

ios - 在 UITableView 的自动布局中带有填充的多行 UILabel