How to fix rough scrolling behavior of webView when resizing it?

Viewed 40

Every web browser has some kind of toolbar at the bottom.

When you scroll downwards the toolbar disappears and the page becomes taller.

This looks smooth on Safari and Chrome:

https://www.youtube.com/shorts/vZ2mgcaIcf8

But it looks very rough on every other browser I tested. Because the webView gets resized and rendered again.

Brave Browser:

https://www.youtube.com/shorts/GiZkIYNQVf4

Test it yourself, it looks awful on Microsoft Edge, Opera, DuckDuckGo, Mozilla Firefox and Brave.

What's their secret? How does Safari and Chrome behave so smooth?

Code to initialize the webView:

    self.webView = [[WKWebView alloc] init];
    
    self.webView.scrollView.delegate = self;

    self.webView.frame =
    CGRectMake(0.0,
               0.0,
               self.view.frame.size.width,
               self.view.frame.size.height);
    
    [self.view addSubview:self.webView];

    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.apple.com/iphone-14-pro/"]]];

Code to resize the webView when scrolling:

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    // Uses a global previousContentOffset variable.

    if (scrollView.contentOffset.y > 0.0) {
        
        CGFloat movement = scrollView.contentOffset.y - self.previousContetOffset.y;
        
        CGFloat allowableMovement = 10.0;
        
        // Going downwards.
        if (movement >= allowableMovement) {

            [UIView animateWithDuration:0.2
                             animations:^{
                
                self.webView.frame =
                CGRectMake(0.0,
                           0.0,
                           self.view.frame.size.width,
                           self.view.frame.size.height);
            }];
            
            self.previousContetOffset = scrollView.contentOffset;
        }
        
        // Going upwards.
        if (movement <= -allowableMovement) {
            
            [UIView animateWithDuration:0.2
                             animations:^{
                
                self.webView.frame =
                CGRectMake(0.0,
                           0.0,
                           self.view.frame.size.width,
                           self.view.frame.size.height - 80.0); // Height of toolbar
            }];
            
            self.previousContetOffset = scrollView.contentOffset;
        }
    }
}

EDIT: If you play a bit with the Chrome browser for iOS you will see that the horizontal scroll bar is not at the top when you load a web page. They must manipulate the contentInsets of the scrollView in order to make it look smooth but I have no idea how. I tried it myself to no avail.

0 Answers
Related