timetraveler90
timetraveler90

Reputation: 346

Scrolling to the bottom of the WKWebView programmatically doesn't work

I had some legacy code that should be changed a bit to comply to Apple standards, actually to avoid using UIWebView and change it to WKWebView in order to be able to release the app regularly.

Code in that legacy part that was dedicated for the scrolling of the page to the bottom after loading it was like this, and it was absolutely functional:

    public func webViewDidFinishLoad(_ webView: UIWebView) {
        var scrollHeight: CGFloat = webView.scrollView.contentSize.height - webView.bounds.size.height
        if 0.0 > scrollHeight {
            scrollHeight = 0.0
        }
        webView.scrollView.setContentOffset(CGPoint.init(x: 0.0, y: scrollHeight), animated: true)
    }

And since I had to get rid of UIWebView components from the app I adjusted the code like this. Added the WebKit import, make my class conform to the WKNavigationDelegate protocol and set the delegate like this: webView.navigationDelegate = self and implemented appropriate function as follows:

public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    var scrollHeight: CGFloat = webView.scrollView.contentSize.height - webView.bounds.size.height
    if 0.0 > scrollHeight {
        scrollHeight = 0.0
    }
    webView.scrollView.setContentOffset(CGPoint.init(x: 0.0, y: scrollHeight), animated: true)
}

Right now I do not understand where I am making mistake when the WKWebView refuses to scroll the page to the bottom?

Upvotes: 0

Views: 1119

Answers (1)

timetraveler90
timetraveler90

Reputation: 346

Found the solution, removed the code I used and switched it to the following one:

    public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
          webView.evaluateJavaScript("var scrollingElement = (document.scrollingElement || document.body); scrollingElement.scrollTop = scrollingElement.scrollHeight;")
}

Upvotes: 3

Related Questions