首页 > 解决方案 > 带有baselineOffset的NSAttributedString会导致最后一行被截断

问题描述

我有一个属性字符串,它有一个设置的基线偏移量,它按我的预期呈现。

在此处输入图像描述

问题是当我将任何其他样式(颜色、删除线、链接等)添加到字符串的一部分时,文本的位置错误,因此不会呈现最后一行。

在此处输入图像描述

有没有办法让它正常工作?

我最初的目标是将行高更改为小于字体的默认值,然后移动基线,以便某些字符的顶部不会被切断(如 $)。


这是我可以制作的最简单的版本,可以在操场上重现它。

import UIKit
​
let baselineOffset: Float = 5
​
let defaultAttributes: [NSAttributedString.Key: Any] = [
    .baselineOffset: NSNumber(value: baselineOffset),
]
​
let middleAttributes: [NSAttributedString.Key: Any] = [
    .foregroundColor: UIColor.blue,
//    .strikethroughStyle: NSNumber(value: NSUnderlineStyle.single.rawValue)
//    .link: URL(fileURLWithPath: ""),
]
​
let part = NSMutableAttributedString(string: "Lorem ipsum\n", attributes: defaultAttributes)
​
let middlePart = NSMutableAttributedString(attributedString: part)
middlePart.addAttributes(middleAttributes,
                          range: NSRange(location: 0, length: middlePart.length))
​
let string = NSMutableAttributedString()
string.append(part)
string.append(middlePart)
string.append(part)
​
// Remove last newline
string.replaceCharacters(in: NSRange(location: string.length-1, length: 1), with: "")
​
print(string)
​
let label = UILabel()
label.backgroundColor = .white
label.numberOfLines = 0
label.attributedText = string
label.sizeToFit()
label

标签: iosswiftcocoa-touchuilabelnsattributedstring

解决方案


推荐阅读