Search code examples
iosobjective-cuiwebviewuiscrollviewuikit

Disable dragging past top of UIWebView / UIScrollView (the "Pull to refresh" gesture)


I've got a UIWebView that I'd like the user to be able to scroll down, then back up again, but not pull the page back from the top (the gesture normally associated with pull to refresh). I don't want users pulling at it when there's nothing behind it, and nothing'll happen when they do. Call me over-bearing ;)

Can I disable the scrolling when moving up and already at the top of the content, without affecting scrolling down, or back up if not at the top?


Solution

  • You should use :

    webView.scrollView.bounces = NO;
    

    UIWebView conforms to UIScrollViewDelegate. You can implement the delegate method like this :

    - (void)scrollViewDidScroll:(UIScrollView *)scrollView{
        //The webview is is scrolling
        int yPosition = [[_webview stringByEvaluatingJavaScriptFromString: @"scrollY"] intValue];
    
        if([[_webview stringByEvaluatingJavaScriptFromString: @"document.body.offsetHeight"] intValue] - yPosition == _webview.frame.size.height)
        {
            //The user scrolled to the bottom of the webview
            _webview.scrollView.bounces = YES;
        }else if([[_webview stringByEvaluatingJavaScriptFromString: @"document.body.offsetHeight"] intValue] - yPosition > _webview.frame.size.height + 100){
            _webview.scrollView.bounces = NO;
        }
    
    }
    

    I uploaded an XCode project sample here on Google Drive : Sample Code