要在 SwiftUI 文本中显示包含图片的 HTML,并使其高度自适应,可以使用'NSAttributedString' 和 'UITextView' 的组合。

首先,创建一个 'UITextView' 的子类,以便可以使用自定义的 'NSAttributedString' 来显示 HTML:

import SwiftUI

class HTMLTextView: UITextView {
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        isEditable = false
        isScrollEnabled = false
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

然后,在 SwiftUI 中创建一个自定义视图来包装 'HTMLTextView':

import SwiftUI
import UIKit

struct HTMLTextViewWrapper: UIViewRepresentable {
    let htmlText: String
    
    func makeUIView(context: Context) -> HTMLTextView {
        return HTMLTextView()
    }
    
    func updateUIView(_ uiView: HTMLTextView, context: Context) {
        if let attributedText = htmlText.htmlToAttributedString() {
            uiView.attributedText = attributedText
        }
    }
}

 extension String {
    func htmlToAttributedString() -> NSAttributedString? {
        guard let data = data(using: .utf8) else { return nil }
        do {
            return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)
        } catch {
            return nil
        }
    }
}

现在,可以在 SwiftUI 视图中使用 'HTMLTextViewWrapper' 来显示包含图片的 HTML,并使其高度自适应。例如:

import SwiftUI

struct ContentView: View {
    var body: some View {
        HTMLTextViewWrapper(htmlText: "<html><body><img src='https://example.com/image.png' width='200' height='200'></body></html>")
            .frame(height: 200) // 设置视图的初始高度
            .onAppear { 
                UITableView.appearance().backgroundColor = UIColor.clear
            }
    }
}

在上面的示例中,'HTMLTextViewWrapper' 将 HTML 字符串转换为 'NSAttributedString',然后通过 'HTMLTextView' 进行显示。可以通过设置视图的初始高度来控制自适应的高度。

SwiftUI 文本中显示自适应高度的 HTML 图片

原文地址: https://www.cveoy.top/t/topic/pTy4 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录