2

Here is the HTMLStringView struct:

struct HTMLStringView: UIViewRepresentable {

    let htmlContent: String
    var webView: WKWebView = WKWebView()

    func makeUIView(context: Context) -> WKWebView {
        webView.scrollView.isScrollEnabled = false
        return webView
    }

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

}

The WKWebView cannot determine its frame size according to the html content inside. Maybe one could construct a function to determine the height according to the html content? Or, is there easier way to achieve this?

Charlotte L.
  • 143
  • 3
  • 13
  • Similar has been solved in [SwiftUI WKWebView content height issue](https://stackoverflow.com/a/59790493/12299030) – Asperi Jun 09 '20 at 03:44

1 Answers1

1

Set a @State in the View you're working in:

@State private var webViewHeight: CGFloat = .zero

Do this in your func webView:

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!){
        webView.evaluateJavaScript("document.body.scrollHeight", completionHandler: {(height, error) in
            DispatchQueue.main.async {
                self.parent.dynamicHeight = height as! CGFloat
            }
        })
    }

Then in your View do this:

HTMLStringView(dynamicHeight: $webViewHeight, htmlContent: "\(stuff from an API I worked with)")
                    .frame(height: webViewHeight, alignment: .leading)
stinek4
  • 11
  • 1