how to render html in swiftui

how to render html in swiftui?

if i use this code, the layout becomes unresponsive webview and the font can't be resized.

Code Block struct TextCustom: UIViewRepresentable {
  let text: String
  func makeUIView(context: Context) -> WKWebView {
    return WKWebView()
  }
  func updateUIView(_ uiView: WKWebView, context: Context) {
    uiView.loadHTMLString(text, baseURL: nil)
  }
}

and if i use this code, it only showing the first line if the text contains new line code but the rest is not rendered. I got the text from rest-API

Code Block
struct TextCustom: UIViewRepresentable {
  let html: String
  func makeUIView(context: UIViewRepresentableContext<Self>) -> 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
     }
  }
  print(html)
  return label
}
}

The code should work.
Please note that the WebView has a different rendering system than UIKit.
So you don't get the dynamic font size advantage for free.

Code Block
import SwiftUI
import WebKit
struct ContentView: View {
  @State var text = "<html><body><h1>Hello World</h1></body></html>"
   
  var body: some View {
    WebView(text: $text)
      .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
  }
}
struct WebView: UIViewRepresentable {
  @Binding var text: String
   
  func makeUIView(context: Context) -> WKWebView {
    return WKWebView()
  }
   
  func updateUIView(_ uiView: WKWebView, context: Context) {
    uiView.loadHTMLString(text, baseURL: nil)
  }
}
struct ContentView_Previews: PreviewProvider {
  static var previews: some View {
    ContentView()
  }
}

I try this code and it work but you should give an idealHeight I recommend you to give idealHeight 500 CGFloat after that it will work

Code Block SwiftUI
WebView(text: $text)
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, idealHeight: 500, maxHeight: .infinity, alignment: .center)
                .padding()


Use TextView instead of Label.

struct TextCustom: UIViewRepresentable {
  let html: String
  func updateUIView(_ uiView: UITextView, context: UIViewRepresentableContext<Self>) {
    DispatchQueue.main.async {
      let data = Data(self.html.utf8)
      if let attributedString = try? NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) {
        uiView.isEditable = false
        uiView.attributedText = attributedString
      }
    }
  }
  func makeUIView(context: UIViewRepresentableContext<Self>) -> UITextView {
    let label = UITextView()
    return label
  }
}
how to render html in swiftui
 
 
Q