1

I'm in need of rendering a html string in my swiftui app.

I found this: How to show HTML or Markdown in a SwiftUI Text?

But I tried every single solution there and I get a blank screen!

This is my code:

import SwiftUI
import WebKit


struct HTMLStringView: UIViewRepresentable {
    let htmlContent: String

    func makeUIView(context: Context) -> WKWebView {
        return WKWebView()
    }

    func updateUIView(_ uiView: WKWebView, context: Context) {
        uiView.loadHTMLString(htmlContent, baseURL: nil)
    }
}


struct audioInfoView: View {
    
    let longDetails: String

    
    var body : some View{
        
        ScrollView{
            
            ZStack{
                
                HTMLStringView(htmlContent: "<p>\(longDetails)</p>")
                
                //Text(longDetails)
             
                
            }.padding()
        }.padding(.top,50)
        
    }
}

The let longDetails: String is a string with html tags that's being passed on from another view.

If I do Text(longDetails), I can see the text and all the html tags but when I do HTMLStringView(htmlContent: "<p>\(longDetails)</p>"), I see nothing and it only displays a blank screen!

what am I doing wrong?

drago
  • 1,148
  • 2
  • 16
  • 35

1 Answers1

5

WKWebView has a scroll view in it and you also have the HTMLStringView wrapped in a ScrollView, leading to some layout conflicts.

Options:

  1. Remove the outer ScrollView:
var body : some View{
        HTMLStringView(htmlContent: "<p>\(longDetails)</p>")
    }
  1. Pass an explicit height:
var body : some View{
    ScrollView{
        ZStack{
            HTMLStringView(htmlContent: "<p>\(longDetails)</p>")
                .frame(height: 200)
        }.padding()
    }.padding(.top,50)
}

What you choose may vary based on your use case. You may also want to explore .isScrollEnabled on WKWebView if you don't want the WKWebView to be scrollable. And, it seems like you may also end up with a case where you need to find the height of the WKWebView content: How to determine the content size of a WKWebView?

jnpdx
  • 45,847
  • 6
  • 64
  • 94