Skip to content

Instantly share code, notes, and snippets.

@kb100824
Forked from pkuecuekyan/WKWebViewSizeToFit.swift
Created November 16, 2023 12:16
Show Gist options
  • Save kb100824/9ed983f3cc31ac7a8151bac1931bd162 to your computer and use it in GitHub Desktop.
Save kb100824/9ed983f3cc31ac7a8151bac1931bd162 to your computer and use it in GitHub Desktop.
Adjust height of WKWebView frame based on scrollHeight of the webView's content
// Since the WKWebView has no sizeToFit() method, increase the frame height of the webView to
// match the height of the content's scrollHeight
//
// The WKWebView's `navigationDelegate` property needs to be set for the delegate method to be called
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
if webView.isLoading == false {
webView.evaluateJavaScript("document.body.scrollHeight", completionHandler: { [weak self] (result, error) in
if let height = result as? CGFloat {
webView.frame.size.height += height
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment