WKWebView changes its content offset scroll after rotation (orientation changed)

1k Views Asked by At

When I rotate from Portrait to Landscape on my phone web view changes its scroll automatically almost to the bottom of content on the page.

I've tried reloadInputViews also this code does not work as well:

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)
        //webView.reloadInputViews()
        //webView.scrollView.setContentOffset(CGPoint(x: 0, y: 0), animated: false)
        webView.evaluateJavaScript("location.reload();", completionHandler: nil)
    }

Nothing of these won't scroll web view to the top. Actually if possible I don't even need this scroll to be occurred after rotation. I would like to see the web view content starting form the top. No matter which orientation is.

1

There are 1 best solutions below

1
rohanphadte On

If you want your webView to always scroll to the top of the page on rotation, you can implement this code on the ViewController that holds the webView. However, by looking at your commented-out code, it seems that you've already tried something very similar.

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    webView.scrollView.setContentOffset(CGPoint(x: 0, y: -self.webView.scrollView.contentInset.top), animated: false)
}

When I rotate from Portrait to Landscape on my phone web view changes its scroll automatically almost to the bottom of content on the page.

Are you sure this isn't some side effect of your code somewhere? If you create a webView on an empty project, and then go to a sample webpage with scroll (Google search results for example), rotating the phone keeps the webView's scroll position. Further, if you implement the code above in an empty project with a webview, it achieves a scroll to the top of the webpage.