SwiftUI: how to set dynamic size of WKWebView() according to its html content?

Viewed 852

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?

1 Answers

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)
Related