I'm trying to create WebView with autoheight.
I'ts must to display some content in the same way as multiline Text()
: If it's content become bigger - its must automatically enlarge height of my WebView
My code is a set of lame hacks and it's works really bad.
import SwiftUI
import WebKit
@available(OSX 11.0, *)
public struct WebView: View {
@Binding var html: String
public init (html: Binding<String> ){
_html = html
}
public var body: some View {
WebViewWrapper(html: html)
}
}
@available(OSX 11.0, *)
public struct WebViewWrapper: NSViewRepresentable {
let html: String
public func makeNSView(context: Context) -> WKWebView {
return WKWebView()
}
public func updateNSView(_ webView: WKWebView, context: Context) {
webView.loadHTMLString(html, baseURL: nil)
webView.actualateHeight()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) {
webView.actualateHeight()
}
}
}
fileprivate extension WKWebView {
func actualateHeight(){
self.setFrameHeight(1)
self.evaluateJavaScript("document.readyState", completionHandler: { (complete, error) in
if complete != nil {
self.evaluateJavaScript("document.body.scrollHeight", completionHandler: { (height, error) in
if let height = height {
self.setFrameHeight(height as! Float)
}
})
}
})
}
func setFrameHeight(_ height: Float) {
let size = NSSize(width: self.frame.width, height: CGFloat(height) )
self.setFrameSize(size)
self.setBoundsSize(size)
print("YYY \(height)")
}
}
usage:
struct PreferencesView : View {
var model : Config
@ObservedObject var splittedStatusWindow : ConfigProperty<Bool>
@State var text: String = "<html> <style>body{background-color:linen;} H1 {font-size: 50;} .testClass { color: red; } #hell{ color: green;}</style> <body><h1 class='testClass'>Hello World</h1><p id='hell'><strong>hell</strong> yeah!</p></body></html>"
init(model: Config) {
self.model = model
self.splittedStatusWindow = model.splitedStatusWindow
}
var body: some View {
Spacer()
TextField("", text: $text)
Divider()
WebView(html: $text)
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
Divider()
Spacer()
}
}
problems of the code:
- hacky solutions bad autoupdate of size
- size of wrapper around the code is larger than expected. Always.
but expected sth like: