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