NSAttributedString与baselineOffset可能会导致最后一行被切断

问题描述

我有一个属性字符串,该字符串具有设置的基线偏移量,可以按我的期望进行渲染。

enter image description here

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

enter image description here

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

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


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

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

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)