swiftui WKWebView加载html字符串让html图片高度自适应webkit高度自适应
要在SwiftUI中使用WKWebView加载HTML字符串并让其中的图片和WebView自适应高度,可以使用以下步骤:
- 创建一个
WebView的UIViewRepresentable,用于在SwiftUI中包装WKWebView。
import SwiftUI
import WebKit
struct WebView: UIViewRepresentable {
let htmlString: String
func makeUIView(context: Context) -> WKWebView {
return WKWebView()
}
func updateUIView(_ uiView: WKWebView, context: Context) {
uiView.loadHTMLString(htmlString, baseURL: nil)
}
}
- 在需要显示WebView的地方,使用
WebView视图,并传递要加载的HTML字符串。
struct ContentView: View {
let htmlString = """
<html>
<head>
<style>
img {
max-width: 100%;
height: auto;
}
</style>
</head>
<body>
<img src="https://example.com/image.jpg">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</body>
</html>
"""
var body: some View {
WebView(htmlString: htmlString)
}
}
在上面的代码中,我们在HTML中使用了样式来使图片的宽度自适应,并保持高度自动调整。
这样,当你在SwiftUI中显示这个WebView时,它将加载并显示HTML字符串,并确保图片和WebView自适应高度
原文地址: https://www.cveoy.top/t/topic/h6L1 著作权归作者所有。请勿转载和采集!