Maintain scroll position in UIWebView when resizing

I have a UIWebView that changes when the device rotates. When you resize the web page, the scroll position at the top of the page remains unchanged, but as the height of the content changes, you find yourself in a different place at the end of the rotation.

Web view content is text and images that are not scaled to fit. With a smaller width, the text breaks, making it higher.

Is there a good way to keep the scroll position?

+4
source share
2 answers

One way to solve this problem is to configure contentOffset to view the scroll of webviews after the rotation. Due to changes in line breaks in texts, the overall page size may change during rotation.

So, to solve this problem, you need to save the old size of the content of the webviews in the "willRotateToInterfaceOrientation" method, then calculate the relative change in the "didRotateFromInterfaceOrientation" method and adjust the contentOffset content to scroll. (This "almost" solves the problem - I say almost because because of the changes in line breaks you can go one or two lines out of the desired position.)

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration { oldSize = self.webView.scrollView.contentSize; } - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation { CGSize newSize = self.webView.scrollView.contentSize; float xFactor = newSize.width / oldSize.width; float yFactor = newSize.height / oldSize.height; CGPoint newOffset = webView.scrollView.contentOffset; newOffset.x *= xFactor; newOffset.y *= yFactor; webView.scrollView.contentOffset = newOffset; } 
0
source

Take a look at my solution: https://github.com/cxa/WebViewContentPositioner . In short, I use document.caretRangeFromPoint(0, 0) to capture the Range and insert an element to track its position. After resizing, use the captured Range information to determine the position.

0
source

Source: https://habr.com/ru/post/1393086/


All Articles