SiwiftUI:UITextView 正在切换到 TextKit 1

use*_*121 2 uitextview textkit swiftui ios16

我收到日志消息UITextView 正在切换到 TextKit 1 兼容模式,因为它的 textStorage 包含与NSAttributedString使用的TextKit 2 不兼容的属性。documentType: NSAttributedString.DocumentType.html

例子:

func makeUIView(context: Context) -> UITextView {
    let textView = UITextView()
    return textView
}

func updateUIView(_ uiView: UITextView, context _: Context) {
    var currentText: NSAttributedString?
    let htmlString = "<html><body><h1>Example</h1></body></html>"
    
    guard let encodedData = htmlString.data(using: .utf8) else {
        fatalError("Could not encode HTML data")
    }
    
    do {
        currentText = try NSAttributedString(data: encodedData,
                                             options: [
                                                .documentType: NSAttributedString.DocumentType.html,
                                                .characterEncoding: String.Encoding.utf8.rawValue
                                             ],
                                             documentAttributes: nil)
    } catch let error as NSError {
        fatalError(error.localizedDescription)
    } catch {
        fatalError("error")
    }
    
    uiView.attributedText = currentText
}
Run Code Online (Sandbox Code Playgroud)

有什么想法如何解决它吗?

mah*_*han 6

您可以选择 TextKit 1 或 TextKit 2。

在 iOS 16+ 中,默认UITextView使用TextKit 2. 如果您想使用TextKit 1,请UITextView使用此构造函数构造:

init(usingTextLayoutManager: Bool)
Run Code Online (Sandbox Code Playgroud)

创建一个新的文本视图,带或不带文本布局管理器,具体取决于您指定的布尔值。

https://developer.apple.com/documentation/uikit/uitextview

如果usingTextLayoutManager为 true,UITextView则使用TextKit 2. 如果是falseTextKit 1将被使用。

文本工具包2

let textView = UITextView(usingTextLayoutManager: true)
Run Code Online (Sandbox Code Playgroud)

文本工具包1

let textView = UITextView(usingTextLayoutManager: false)
Run Code Online (Sandbox Code Playgroud)

于也亦复如是NSTextView