在 macOS Sonoma (23A5312d) 上,在
NSAttributedString
中使用 NSTextView
时,会出现 HTML 表格布局问题。
考虑以下 Swift 代码:
override func viewDidLoad() {
super.viewDidLoad()
let html = """
<table width="100%" border="1" style="color: white">
<tr>
<td align="left">Left</td>
<td align="right">Right</td>
</tr>
</table>
"""
let data = Data(html.utf8)
let definition = try! NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: NSNumber(value: String.Encoding.utf8.rawValue)], documentAttributes: nil)
let frameRect = NSRect(x: 100, y: 0, width: 300, height: 200)
let textView = NSTextView(frame: frameRect)
textView.textStorage?.setAttributedString(definition)
textView.backgroundColor = .clear
view.addSubview(textView)
}
在 macOS Ventura 上,它看起来像这样:
在 macOS Sonoma 上,它看起来像这样:
鼠标悬停时,会出现 HTML(尽管已损坏):
向 Apple 报告的问题为 FB12800496,他们回应称这是由于“降级到 TextKit 1 来处理表格内容”。他们建议使用“TextKit1 NSTextView via init(usingTextLayoutManager:)”,以下代码解决了 HTML 最初不出现的问题:
let textView = NSTextView(usingTextLayoutManager: false)
textView.frame = frameRect
Apple 反馈写道,布局问题来自“WebKit 的 NSAttributedString 翻译”,并且“TextKit 的内部 WebKit1 翻译器”已正确处理。
是否可以调用“WebKit1翻译器”?
更新2023-11-01
按照 Apple TextKit 和文本视图中的新增功能开发人员视频中的“以编程方式选择退出”说明强制使用 TextKit 1 会导致不同的布局问题: