uilabel - 将 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决定,或者至少是一些东西,除了文本的前景颜色......
解决方案
推荐阅读
- ant-design-pro - 使用 antdesignpro 自定义语言环境
- linux - u-boot:cmd mdtparts 找不到 nor0
- github - 添加依赖项?
- java - 如何处理精度点?
- java - 卡夫卡 - 突触
- c# - 为什么一类给出 CS0311 错误而另一类没有?
- sublimetext3 - error Autoprefixer sublime text 3. 如何解决这个问题?
- c# - 在iframe multiview c#中的webmethod中返回html页面
- flutter - 在 Flutter 中的 PageView.builder 上查看索引号
- javascript - 如何使用 JavaScript 在 div 标签中加载 HTML