Skip to content

Instantly share code, notes, and snippets.

@imbradbrown
Created April 25, 2018 12:23
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imbradbrown/6e0708b096cf36aa450c7c3cd472b662 to your computer and use it in GitHub Desktop.
Save imbradbrown/6e0708b096cf36aa450c7c3cd472b662 to your computer and use it in GitHub Desktop.
WKWebView scroll to anchor location useful if having to add header/footers that scroll with it
@IBOutlet var scrollView: UIScrollView!
var webView: WKWebView!
/// container for the webView in the storyboard
@IBOutlet var webViewContainer: UIView!
/// height of the container
@IBOutlet var webViewHeightConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
webView = WKWebView()
webView.isOpaque = false
webView.backgroundColor = UIColor.clear
webView.scrollView.backgroundColor = UIColor.clear
webView.navigationDelegate = self
webView.scrollView.isScrollEnabled = false
webViewContainer.addSubview(webView)
webView.autoPinEdgesToSuperviewEdges()
webView.loadHTMLString(rawHTML, baseURL: nil) // html from your source, file, etc.
}
extension YourViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
if navigationAction.navigationType == .linkActivated,
let link = navigationAction.request.url?.absoluteString,
link.starts(with: "about:blank%23") {
if let anchor = link.replaceMatches(in: "about:blank%23", withFormat: "") {
let javascript = "document.getElementById('\(anchor)').offsetTop"
self.webView.evaluateJavaScript(javascript) { [weak self] (result, error) in
if let offset = result as? CGFloat {
self?.scrollView.contentOffset.y = offset
}
}
}
}
decisionHandler(WKNavigationActionPolicy.allow)
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
var height = max(webView.frame.size.height, webView.scrollView.contentSize.height)
self.webView.evaluateJavaScript("document.body.offsetHeight", completionHandler: { [weak self] (result, error) in
// if the document was a PDF result will be nil. Otherwise it'll be the height.
if let resultAsCGFloat = result as? CGFloat {
// Need to add a bit to the bottom to prevent clipping
height = max(height, resultAsCGFloat + 20)
}
self?.webViewHeightConstraint.constant = height
self?.webView.setNeedsUpdateConstraints()
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment