在 SwiftUI 中,可以使用 UIViewRepresentable 协议来包装 UIWebView,并在其中监听 WebView 内容高度的变化。具体步骤如下:

  1. 创建一个新的 SwiftUI View,名为 WebView
import SwiftUI
import WebKit

struct WebView: UIViewRepresentable {
    @Binding var contentHeight: CGFloat
    
    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }
    
    func makeUIView(context: Context) -> WKWebView {
        let webView = WKWebView()
        webView.navigationDelegate = context.coordinator
        return webView
    }
    
    func updateUIView(_ webView: WKWebView, context: Context) {
        guard let url = URL(string: "https://www.example.com") else { return }
        let request = URLRequest(url: url)
        webView.load(request)
    }
    
    class Coordinator: NSObject, WKNavigationDelegate {
        var parent: WebView
        
        init(_ parent: WebView) {
            self.parent = parent
        }
        
        func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
            webView.evaluateJavaScript("document.readyState") { (result, error) in
                if let readyState = result as? String, readyState == "complete" {
                    webView.evaluateJavaScript("document.body.scrollHeight") { (result, error) in
                        if let height = result as? CGFloat {
                            self.parent.contentHeight = height
                        }
                    }
                }
            }
        }
    }
}
  1. 在你的主视图中使用 WebView
struct ContentView: View {
    @State private var webViewContentHeight: CGFloat = 0
    
    var body: some View {
        VStack {
            WebView(contentHeight: $webViewContentHeight)
                .frame(height: webViewContentHeight)
        }
    }
}

在上面的例子中,WebView 是一个 UIViewRepresentable,它用 WKWebView 来显示网页内容。WebView 中的 contentHeight 是一个绑定属性,用于存储 WebView 内容的高度,并在 WebView 内容高度变化时更新。

WebView 中的 Coordinator 是一个 WKNavigationDelegate,用于监听 WebView 加载完成事件。当 WebView 加载完成时,通过 JavaScript 代码获取网页内容高度,并将其赋值给 contentHeight 属性。然后,主视图中的 WebView 的高度将根据 webViewContentHeight 的变化而变化

swiftUI kvo 监听 webview content 的高度变化

原文地址: https://www.cveoy.top/t/topic/iccr 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录