How to show HTML or Markdown in a SwiftUI Text?

后端 未结 5 1524
孤城傲影
孤城傲影 2020-12-31 12:39

How can I set a SwiftUI Text to display rendered HTML or Markdown?

Something like this:

Text(HtmlRenderedString(fromString: \"

        
5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-31 13:03

    If you don't need to specifically use a Text view. You can create a UIViewRepresentable that shows a WKWebView and simple call loadHTMLString().

    import WebKit
    import SwiftUI
    
    struct HTMLStringView: UIViewRepresentable {
        let htmlContent: String
    
        func makeUIView(context: Context) -> WKWebView {
            return WKWebView()
        }
    
        func updateUIView(_ uiView: WKWebView, context: Context) {
            uiView.loadHTMLString(htmlContent, baseURL: nil)
        }
    }
    

    In your body simple call this object like this:

    import SwiftUI
    
    struct Test: View {
        var body: some View {
            VStack {
                Text("Testing HTML Content")
                Spacer()
                HTMLStringView(htmlContent: "

    This is HTML String

    ") Spacer() } } } struct Test_Previews: PreviewProvider { static var previews: some View { Test() } }

提交回复
热议问题