{/'title/':/'SwiftUI WKWebView 加载 HTML 字符串并自适应高度及图片高度/',/'description/':/'本文介绍如何在 SwiftUI 中使用 WKWebView 加载 HTML 字符串,并通过 GeometryReader 动态计算 WebView 的高度,使其能够根据内容自适应高度,同时确保图片也能正确显示。/',/'keywords/':/'SwiftUI, WKWebView, HTML, 自适应高度, 图片高度, GeometryReader, onPreferenceChange/',/'content/':/'import SwiftUI//nimport WebKit//n//nstruct ContentView: View {//n @State private var webViewHeight: CGFloat = 100//n //n var body: some View {//n VStack {//n GeometryReader { geometry in//n WebView(htmlString: /'

This is some HTML content with an image:
<img src=///'https://example.com/image.jpg///'>

/')//n .frame(height: webViewHeight)//n .onPreferenceChange(WebViewHeightPreferenceKey.self) { height in//n webViewHeight = height//n }//n }//n .frame(height: webViewHeight)//n //n Text(/'WebView Height: //(webViewHeight)/')//n }//n }//n}//n//nstruct WebView: UIViewRepresentable {//n let htmlString: String//n //n func makeUIView(context: Context) -> WKWebView {//n let webView = WKWebView()//n return webView//n }//n //n func updateUIView(_ uiView: WKWebView, context: Context) {//n uiView.loadHTMLString(htmlString, baseURL: nil)//n uiView.scrollView.isScrollEnabled = false//n uiView.navigationDelegate = context.coordinator//n }//n //n func makeCoordinator() -> Coordinator {//n Coordinator(self)//n }//n //n class Coordinator: NSObject, WKNavigationDelegate {//n let 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.documentElement.scrollHeight/', completionHandler: { (height, error) in//n if let height = height as? CGFloat {//n webView.frame.size.height = height//n webView.scrollView.contentSize.height = height//n parent.updateWebViewHeight(height)//n }//n })//n }//n })//n }//n }//n}//n//nstruct WebViewHeightPreferenceKey: PreferenceKey {//n static var defaultValue: CGFloat = 0//n //n static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {//n value = nextValue()//n }//n}//n//nextension WebView {//n func updateWebViewHeight(_ height: CGFloat) {//n DispatchQueue.main.async {//n webViewHeight = height//n }//n }//n}/

SwiftUI WKWebView 加载 HTML 字符串并自适应高度及图片高度

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

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