将NSAttributedString与多个frontendColor一起使用会使UILabel中的文本看起来比预期的低

时间:2019-02-12 10:07:50

标签: uilabel nsattributedstring textkit

演示

https://github.com/NSFish/NSAttributedStringWithMultipleForegroundColor

说明

在这里,我有一个尽可能简单的UILabel

let label = UILabel()
label.backgroundColor = UIColor.gray
label.numberOfLines = 2
view.addSubview(label)
// autolayout stuff..

然后配置NSAttributedString以满足设计者的意图

let content = " 自营  回力/WARRIOR 轮胎 215/65R16 98H SR1"
let attributedText = NSMutableAttributedString.init(string: content)
let font = UIFont.systemFont(ofSize: 16)
let baselineOffset = (lineHeight - font.lineHeight) / 4
let attributes: [NSAttributedString.Key : Any] = [NSAttributedString.Key.font: font,
                                                  NSAttributedString.Key.foregroundColor: UIColor.black,
                                                  NSAttributedString.Key.baselineOffset: Int(baselineOffset)]

attributedText.setAttributes(attributes, range: NSRange.init(location: 0, length: content.count))

let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.maximumLineHeight = lineHeight
paragraphStyle.minimumLineHeight = lineHeight
        attributedText.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range: NSRange.init(location: 0, length: content.count))

label.attributedText = attributedText

内容字符串出现在UILabel的中心,与预期的一样。但是当我更改前两个字符的前景色时,事情开始出错

// text looks lower
var prefixAttributes = attributes
prefixAttributes[NSAttributedString.Key.foregroundColor] = UIColor.white
attributedText.setAttributes(prefixAttributes, range: NSRange.init(location: 0, length: 5))
attributedText.setAttributes(attributes, range: NSRange.init(location: 5, length: content.count - 5))
// text in the center, works
// attributedText.setAttributes(attributes, range: NSRange.init(location: 0, length: content.count))

这里唯一的区别是将范围(0,5)的前景色更改为白色。

结果

before after

问题

我对TextKit不太熟悉,但是我确实知道UILabel中文本的位置应该由baselineOffset决定,或者至少由某些东西决定,但是文本的前景色...

0 个答案:

没有答案