Created
October 24, 2023 17:05
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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