首页 > 解决方案 > 将 NSAttributedString 与多个 foregroundColor 一起使用会使 UILabel 中的文本看起来低于预期

问题描述

演示

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))

这里唯一的区别是 range(0, 5) 处的前景颜色更改为白色。

结果

前 后

问题

我对TextKit不是很熟悉,但我知道UILabel中文本的位置应该由baselineOffset决定,或者至少是一些东西,除了文本的前景颜色......

标签: uilabelnsattributedstringtextkit

解决方案


推荐阅读