How to show HTML or Markdown in a SwiftUI Text?

后端 未结 5 1496
孤城傲影
孤城傲影 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:25

    Since I have found another solution I will like to share it with you.

    Create a new View Representable

    struct HTMLText: UIViewRepresentable {
    
       let html: String
    
       func makeUIView(context: UIViewRepresentableContext) -> UILabel {
            let label = UILabel()
            DispatchQueue.main.async {
                let data = Data(self.html.utf8)
                if let attributedString = try? NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) {
                    label.attributedText = attributedString
                }
            }
    
            return label
        }
    
        func updateUIView(_ uiView: UILabel, context: Context) {}
    }
    

    And use it later like this:

    HTMLText(html: "

    Your html string

    ")

提交回复
热议问题