要使 WKWebView 加载的 HTML 字符串自适应高度,可以使用 WebView 的 `navigationDelegate` 属性来监听网页加载完成,并在网页加载完成后获取网页内容的高度,然后将 WebView 的高度调整为网页内容的高度。\n\n这里是一个示例代码:\n\nswift\nimport SwiftUI\nimport WebKit\n\nstruct WebView: UIViewRepresentable {\n let htmlString: String\n \n func makeUIView(context: Context) -> WKWebView {\n let webView = WKWebView()\n webView.navigationDelegate = context.coordinator\n return webView\n }\n \n func updateUIView(_ uiView: WKWebView, context: Context) {\n uiView.loadHTMLString(htmlString, baseURL: nil)\n }\n \n func makeCoordinator() -> Coordinator {\n Coordinator(self)\n }\n \n class Coordinator: NSObject, WKNavigationDelegate {\n var parent: WebView\n \n init(_ parent: WebView) {\n self.parent = parent\n }\n \n func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {\n webView.evaluateJavaScript("document.readyState", completionHandler: { (complete, error) in\n if complete != nil {\n webView.evaluateJavaScript("document.body.scrollHeight", completionHandler: { (height, error) in\n if let height = height as? CGFloat {\n webView.frame.size.height = height\n }\n })\n }\n })\n }\n }\n}\n\nstruct ContentView: View {\n var body: some View {\n ScrollView {\n WebView(htmlString: "<html><body><h1>Hello, World!</h1></body></html>")\n .frame(height: 500)\n }\n }\n}\n\n\n在上述代码中,`WebView` 是一个遵循 `UIViewRepresentable` 协议的结构体,它创建了一个 `WKWebView` 实例,并设置了 `navigationDelegate` 为自定义的 `Coordinator` 类。在 `Coordinator` 类中,我们实现了 `webView(:didFinish:)` 方法,该方法会在网页加载完成后被调用。在该方法中,我们使用 `evaluateJavaScript(:completionHandler:)` 方法获取网页内容的高度,并将 WebView 的高度设置为网页内容的高度。\n\n在 `ContentView` 中,我们使用 `ScrollView` 将 WebView 包装起来,并设置 WebView 的高度为 500。这样,当 WebView 加载 HTML 字符串后,它的高度会自动调整为网页内容的高度。

SwiftUI WKWebView 自适应高度加载 HTML 字符串

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

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