我需要减小文本大小以适应特定区域的宽度。文本包含一些不同的格式设置(主要是文本颜色),所以我使用 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 对其进行了测试,但问题仍然存在。
最佳答案
似乎是 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/