Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect Scrollview bounce - iOS

I would like to implement "pull down to refresh" type effect on a UIScrollview. On detecting "top" bounce of the scrollview, the view should refresh some of the components. How can I detect the "top bounce" of UIScrollview? I tried the delegate "scrollViewWillBeginDragging" but did not work.

like image 256
DonDyck Avatar asked Dec 27 '13 17:12

DonDyck


People also ask

What is Scrollview bounces?

If the value of this property is YES , the scroll view bounces when it encounters a boundary of the content. Bouncing visually indicates that scrolling has reached an edge of the content. If the value is NO , scrolling stops immediately at the content boundary without bouncing. The default value is YES .

What is UIScrollView?

UIScrollView is the superclass of several UIKit classes, including UITableView and UITextView . A scroll view is a view with an origin that's adjustable over the content view. It clips the content to its frame, which generally (but not necessarily) coincides with that of the app's main window.


2 Answers

Implement scrollViewDidScroll:, and check the value of scrollView.contentOffset.y -- it will be negative when you pull down, and go back to 0 (or near 0) when it bounces back. Depending on what condition you want to meet to do the refresh, you could set a flag when that value goes to a specific negative value, and then do the refresh when it goes back to near 0. Something like this:

-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.y < -50) _metNegativePullDown = YES;

    if (fabs(scrollView.contentOffset.y) < 1 && _metNegativePullDown) {
        //do your refresh here
        _metNegativePullDown = NO;
    }
}
like image 181
rdelmar Avatar answered Oct 23 '22 16:10

rdelmar


For the record, i'm detecting both bounces on Swift 4 using this category:

extension UIScrollView {
    var isBouncing: Bool {
        var isBouncing = false
        if contentOffset.y >= (contentSize.height - bounds.size.height) {
            // Bottom bounce
            isBouncing = true
        } else if contentOffset.y < contentInset.top {
            // Top bounce
            isBouncing = true
        }
        return isBouncing
    }
}

Things to consider

  • In this case i'm just checking top content inset, if you are going to use bottom inset some tweaking must be necessary
  • If your scroll view is direct child of viewcontroller's view and has top constraint to superview instead of top safe area margin this will not do the trick perfect, more tweaking will be necessary
like image 34
buguibu Avatar answered Oct 23 '22 14:10

buguibu