Skip to content

Instantly share code, notes, and snippets.

@JadenGeller
Created October 24, 2023 17:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JadenGeller/aaddc2f2c3c623dfe2b9c339f5ac9aaa to your computer and use it in GitHub Desktop.
Save JadenGeller/aaddc2f2c3c623dfe2b9c339f5ac9aaa to your computer and use it in GitHub Desktop.
WKWebView in SwiftUI with intrinsic sizing based on the scrollWidth and scrollHeight of the page
import SwiftUI
import WebKit
struct WebView: NSViewRepresentable {
var url: URL
class Coordinator: NSObject, WKNavigationDelegate {
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
webView.evaluateJavaScript("document.readyState", completionHandler: { (complete, error) in
if complete != nil {
webView.evaluateJavaScript("document.body.scrollWidth", completionHandler: { (width, error) in
let width = width as! CGFloat
(webView.superview as! View).width = width
})
webView.evaluateJavaScript("document.body.scrollHeight", completionHandler: { (height, error) in
let height = height as! CGFloat
(webView.superview as! View).height = height
})
}
})
}
}
func makeCoordinator() -> Coordinator {
Coordinator()
}
class View: NSView {
required init?(coder: NSCoder) {
fatalError()
}
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
}
override var isFlipped: Bool {
true
}
var width: CGFloat = 300 {
didSet {
invalidateIntrinsicContentSize()
}
}
var height: CGFloat = 300 {
didSet {
invalidateIntrinsicContentSize()
}
}
override var intrinsicContentSize: NSSize {
.init(width: width, height: height)
}
}
func makeNSView(context: Context) -> View {
let view = View()
view.setContentHuggingPriority(.required, for: .horizontal)
view.setContentHuggingPriority(.required, for: .vertical)
let webView = WKWebView()
webView.navigationDelegate = context.coordinator
webView.autoresizingMask = [.width, .height]
view.addSubview(webView)
return view
}
func updateNSView(_ view: View, context: Context) {
DispatchQueue.main.async {
let request = URLRequest(url: url)
(view.subviews[0] as! WKWebView).load(request)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment