SwiftUI 解析 HTML 字符串:使用 NSAttributedString 渲染富文本
`import SwiftUI
struct HTMLTextView: UIViewRepresentable {
var htmlString: String
func makeUIView(context: Context) -> UITextView {
let textView = UITextView()
textView.isEditable = false
return textView
}
func updateUIView(_ uiView: UITextView, context: Context) {
if let attributedString = htmlString.htmlToAttributedString {
uiView.attributedText = attributedString
} else {
uiView.attributedText = NSAttributedString(string: htmlString)
}
}
}
extension String {
var htmlToAttributedString: NSAttributedString? {
guard let data = data(using: .utf8) else {
return NSAttributedString()
}
do {
return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil)
} catch {
return NSAttributedString()
}
}
}
struct ContentView: View {
var body: some View {
VStack {
HTMLTextView(htmlString: "Hello, World!")
.frame(height: 100)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
```在 SwiftUI 中使用 NSAttributedString 解析和渲染 HTML 字符串,构建富文本视图。本文将提供详细示例代码,帮助您轻松实现这一功能。*代码示例:首先,需要创建一个遵循 UIViewRepresentable 协议的自定义视图 HTMLTextView。在 makeUIView 方法中创建 UITextView 对象并设置为不可编辑。在 updateUIView 方法中,将 HTML 字符串转换为 NSAttributedString 并将其设置为 UITextView 的 attributedText 属性。最后,在 ContentView 中使用 HTMLTextView 视图来显示 HTML 字符串。关键点: 使用 NSAttributedString 对象来表示富文本。 利用 htmlToAttributedString 扩展方法将 HTML 字符串转换为 NSAttributedString 对象。 使用 UITextView 视图来显示富文本内容。通过以上步骤,您可以轻松地在 SwiftUI 中解析和渲染 HTML 字符串,构建功能强大的富文本视图。
原文地址: https://www.cveoy.top/t/topic/pPLx 著作权归作者所有。请勿转载和采集!