问题描述
我需要减小文本大小以适合特定的区域宽度。文本包含一些不同的格式设置(主要是文本颜色),因此我正在使用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)的设备上对其进行了测试,并且带有属性字符串的字体重新缩放可以正常工作。
UPDATE 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中已修复
,您可以通过StoryBoard / Interface Builder或像这样以编程方式简单地将标签的最小比例因子设置为0.5。
Yourlabel.minimumScaleFactor = 0.5