import SwiftUI import WebKit struct WebView: UIViewRepresentable { let htmlContent: String let settings: Settings let onHeightChange: (CGFloat) -> Void @Environment(\.colorScheme) private var colorScheme func makeUIView(context: Context) -> WKWebView { let webView = WKWebView() webView.navigationDelegate = context.coordinator webView.scrollView.isScrollEnabled = false webView.isOpaque = false webView.backgroundColor = UIColor.clear // 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 isDarkMode = colorScheme == .dark // Font Settings aus Settings-Objekt let fontSize = getFontSize(from: settings.fontSize ?? .extraLarge) let fontFamily = getFontFamily(from: settings.fontFamily ?? .serif) let styledHTML = """ \(htmlContent) """ webView.loadHTMLString(styledHTML, baseURL: nil) } func makeCoordinator() -> WebViewCoordinator { WebViewCoordinator() } private func getFontSize(from fontSize: FontSize) -> Int { switch fontSize { case .small: return 14 case .medium: return 16 case .large: return 18 case .extraLarge: return 20 } } private func getFontFamily(from fontFamily: FontFamily) -> String { switch fontFamily { case .system: return "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif" case .serif: return "'Times New Roman', Times, 'Liberation Serif', serif" case .sansSerif: return "'Helvetica Neue', Helvetica, Arial, sans-serif" case .monospace: return "'SF Mono', Menlo, Monaco, Consolas, 'Liberation Mono', monospace" } } } 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 } }