SwiftUI如何包装WKWebView以使其在HTML加载后自动调整大小

时间:2020-01-22 20:54:29

标签: uitableview swiftui wkwebview autosizing

我将WKWebView放置在“列表”单元格中,并希望将此单元格自动调整为加载到WKWebView的内容的高度。我已经试过了这样的代码,但是没有用

struct WebView: UIViewRepresentable {

    let url: URL?
    let html: String?

    let didFail: (WKNavigation) -> Void
    let didFinish: (WKNavigation) -> Void

    @Binding var contentHeight : CGFloat

    init(html: String, contentHeight: Binding<CGFloat> = .constant(0), didFail: @escaping (WKNavigation) -> Void = { _ in }, didFinish: @escaping (WKNavigation) -> Void = { _ in }) {
        self.url = nil
        self.html = html

        self.didFinish = didFinish
        self.didFail = didFail

        self._contentHeight = contentHeight
    }

    init(url: URL, contentHeight: Binding<CGFloat> = .constant(0), didFail: @escaping (WKNavigation) -> Void = { _ in }, didFinish: @escaping (WKNavigation) -> Void = { _ in }) {
        self.url = url
        self.html = nil

        self.didFinish = didFinish
        self.didFail = didFail

        self._contentHeight = contentHeight
    }

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    func makeUIView(context: Context) -> WKWebView {

        let webView = WKWebView()
        webView.navigationDelegate = context.coordinator
        webView.uiDelegate = context.coordinator

        if let url = url {
            let request = URLRequest(url: url)
            webView.load(request)
        } else if let html = html {
            webView.loadHTMLString(html, baseURL: nil)
        }

        return webView
    }

    func updateUIView(_ webView: WKWebView, context: Context) {

    }

    class Coordinator : NSObject, WKNavigationDelegate, WKUIDelegate {

        private let parent: WebView

        init(_ parent: WebView) {
            self.parent = parent
        }

        func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {

            parent.didFail(navigation)
        }

        func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
            webView.evaluateJavaScript("document.readyState", completionHandler: { (ready, error) in
                if ready != nil {
                    webView.evaluateJavaScript("document.documentElement.scrollHeight", completionHandler: { (height, error) in

                        if let contentHeight = height as? CGFloat {
                            self.parent.contentHeight = contentHeight
                        }
                    })
                }
            })

            parent.didFinish(navigation)
        }

    }
}

即使通过.frame(height: contentHeight)设置@State也不起作用。

0 个答案:

没有答案