我正在使用WebView加载HTML内容。
当我在WebView中加载HTML内容时,它会正确显示。但是当我使用新的HTML内容刷新WebView时,问题就出现了。
例如:我的第一个HTML内容高度为900,它可以正确显示,然后我重新加载WebView,将其与高度为400的新HTML内容一起使用,但WebView不会缩小并适应新高度的内容。它仍然保持原来的900高度。
因此,似乎WebView能够从先前加载的较少内容重新调整大小以适应较多内容,但无法在新内容比先前加载的内容少时重新调整大小。
WebView
struct WebView: UIViewRepresentable {
@State var htmlString: String
@Binding var dynamicHeight: CGFloat
func makeUIView(context: Context) -> WKWebView {
let webView: WKWebView = WKWebView()
webView.navigationDelegate = context.coordinator
webView.scrollView.bounces = false
webView.backgroundColor = .clear
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.documentElement.scrollHeight", completionHandler: { (result, error) in
if let height = result as? CGFloat {
self.parent.dynamicHeight = height
}
})
}
})
}
}
}
任何我使用 WebView 的内容
struct WebTest: View {
@ObservedObject var viewModel = NewsVM()
@State var index: Int = 0
@State var newID: String = ""
let screen = UIScreen.main.bounds
let formatString = "<html><head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=0\"><script type=\"text/javascript\" src=\"https://platform.twitter.com/widgets.js\"></script><style>@media (prefers-color-scheme: dark) { body { background-color: #1c1c1e; color: white; }} img,iframe,blockquote {\n\t\t\tmax-width: \(UIScreen.main.bounds.width - 24);\n\t\t\theight: auto\n\t\t}\n\t\t</style></head><body><span style=\"font-family: '-apple-system', 'HelveticaNeue'; font-size:17\">%@</span></body></html>"
@State private var webViewHeight: CGFloat = .zero
init(id:String) {
viewModel.fetchNews(id: id)
self.newID = id
}
var body: some View {
Group{
if self.viewModel.news.count > 0 {
ModelPages(self.viewModel.news, currentPage: self.$index, wrap: false, hasControl: false) { pageIndex, new in
ScrollView(.vertical, showsIndicators: false){
Text("Height: \(self.webViewHeight)").padding()
WebView(htmlString: String(format: self.formatString, new.content), dynamicHeight: self.$webViewHeight)
.frame(width: self.screen.width - 16)
.frame(height: self.webViewHeight)
.tag(pageIndex)
.padding(.horizontal, 8)
}
}
}else{
Group{
if self.viewModel.error == true{
ConnectionError()
}else{
LoadingView()
}
}
}
}
}
}