Last Updated: February 25, 2016
·
2.269K
· brainfree

A quick pull-to-refresh implementation

This implementation requires you manually add a view to the scrollView/tableView called pullToRefreshView above the 0,0 contentOffset. I'm also using a pullToRefreshTriggered boolean ivar.

I'm sure there are other ways of doing this, but this is the one I came up with.

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    float yOffset = scrollView.contentOffset.y;
    float refreshOffset = self.pullToRefreshView.frame.origin.y;
    static CGPoint lastOffset;

    self.pullToRefreshView.alpha = yOffset / refreshOffset;

    if (scrollView.tracking) {
        if (yOffset < refreshOffset) {
            pullToRefreshTriggered = YES;
            self.pullToRefreshView.label.text = @"Release to Sync";
        } else {
            pullToRefreshTriggered = NO;
            self.pullToRefreshView.label.text = @"Pull to Sync";
        }
    } else {
        if (self.pullToRefreshTriggered) {
            self.pullToRefreshTriggered = NO;

            [scrollView setContentOffset:lastOffset animated:NO];
            [UIView animateWithDuration:0.5f delay:0.0f options:UIViewAnimationOptionCurveEaseOut animations:^{
                [scrollView setContentOffset:CGPointMake(0, refreshOffset) animated:NO];
            } completion:nil];

            // Add refresh code here. The table will pause showing the header until the setContentOffset call below.
            self.pullToRefreshView.label.text = @"Syncing...";

            [scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
        }
    }
    lastOffset = scrollView.contentOffset;
}