import SwiftUI import WebKit struct WebView: UIViewRepresentable { let htmlContent: String let onHeightChange: (CGFloat) -> Void func makeUIView(context: Context) -> WKWebView { let webView = WKWebView() webView.navigationDelegate = context.coordinator webView.scrollView.isScrollEnabled = false // Message Handler hier einmalig hinzufügen webView.configuration.userContentController.add(context.coordinator, name: "heightUpdate") context.coordinator.onHeightChange = onHeightChange return webView } func updateUIView(_ webView: WKWebView, context: Context) { // Nur den HTML-Inhalt laden, keine Handler-Konfiguration context.coordinator.onHeightChange = onHeightChange let styledHTML = """ \(htmlContent) """ webView.loadHTMLString(styledHTML, baseURL: nil) } func makeCoordinator() -> WebViewCoordinator { WebViewCoordinator() } } class WebViewCoordinator: NSObject, WKNavigationDelegate, WKScriptMessageHandler { var onHeightChange: ((CGFloat) -> Void)? func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { if navigationAction.navigationType == .linkActivated { if let url = navigationAction.request.url { UIApplication.shared.open(url) decisionHandler(.cancel) return } } decisionHandler(.allow) } func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { if message.name == "heightUpdate", let height = message.body as? CGFloat { DispatchQueue.main.async { self.onHeightChange?(height) } } } deinit { // Der Message Handler wird automatisch mit der WebView entfernt } }