在 SwiftUI 中,可以使用 'UIViewRepresentable' 将 'WKWebView' 包装成一个 'UIView',然后使用 'Coordinator' 来监听 'WKWebView' 的高度变化。以下是一个示例代码:

import SwiftUI
import WebKit

struct WebView: UIViewRepresentable {
    let request: URLRequest
    
    func makeUIView(context: Context) -> WKWebView {
        let webView = WKWebView()
        webView.scrollView.isScrollEnabled = false
        webView.navigationDelegate = context.coordinator
        webView.addObserver(context.coordinator, forKeyPath: 'scrollView.contentSize', options: .new, context: nil)
        webView.load(request)
        return webView
    }
    
    func updateUIView(_ uiView: WKWebView, context: Context) {
        uiView.load(request)
    }
    
    func makeCoordinator() -> Coordinator {
        Coordinator()
    }
    
    class Coordinator: NSObject, WKNavigationDelegate {
        var webViewHeight: CGFloat = .zero
        
        deinit {
            NotificationCenter.default.removeObserver(self)
        }
        
        override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
            if keyPath == 'scrollView.contentSize' {
                if let webView = object as? WKWebView {
                    webViewHeight = webView.scrollView.contentSize.height
                    // 发送通知
                    NotificationCenter.default.post(name: Notification.Name('WebViewHeightChanged'), object: nil)
                }
            }
        }
    }
}

struct ContentView: View {
    @State private var webViewHeight: CGFloat = .zero
    
    var body: some View {
        VStack {
            WebView(request: URLRequest(url: URL(string: 'https://www.example.com')!))
                .frame(height: webViewHeight)
                .onReceive(NotificationCenter.default.publisher(for: Notification.Name('WebViewHeightChanged'))) { _ in
                    self.webViewHeight = Coordinator().webViewHeight
                }
        }
    }
}

在上述代码中,我们创建了一个名为 'WebView' 的 'UIViewRepresentable',它将 'WKWebView' 包装成一个 'UIView'。我们在 'makeUIView' 方法中创建了 'WKWebView' 实例,并设置了 'navigationDelegate' 为 'context.coordinator',然后使用 'addObserver' 方法来监听 'scrollView.contentSize' 属性的变化。在 'Coordinator' 中,我们实现了 'WKNavigationDelegate' 协议,并在 'observeValue' 方法中监听 'scrollView.contentSize' 的变化,并通过 'NotificationCenter' 发送了一个通知。

在 'ContentView' 中,我们使用 'WebView' 来展示网页,并使用 'onReceive' 方法来监听 'WebView' 高度变化的通知,并更新 'webViewHeight' 的值。这样,我们就可以根据 'webViewHeight' 来设置 'WebView' 的高度了。


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

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