Chris Marshall
Chris Marshall

Reputation: 5332

What's the Best Way to Get a "Pull to Refresh" from a UITableView?

I have a UITableView, and it displays data received from a WiFi-connected device.

I want to do the fairly bog-standard gesture response of dragging a table down, then releasing it, to trigger an update.

I guess I could attach a swipe gesture recognizer to the table's substrate view, but I'm wondering if there is a way to intercept this gesture directly from the table itself.

META:

I've been looking through the various docs and whatnot. I haven't had to do this before, so I never gave it any thought. Now I see that I probably should have thought about it.

If this is an obvious solution, I don't mind being told so, as long as you help me to find the "obvious" remedy. I'll delete this question if it's a bad one.

However, I haven't found a solution, and I'm usually fairly good at that kind of thing.

UPDATE I changed the title to better reflect what I'm asking.

Upvotes: 0

Views: 880

Answers (3)

Chris Marshall
Chris Marshall

Reputation: 5332

This is what I ended up doing. Even though it is not the most "legal" way to do things, it is still highly effective, and absurdly simple:

I set up a scrollview delegate trap, like so, and added it to the delegate class:

//*******************************************
// Reacts to the table's scroller being changed.
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView
                     withVelocity:(CGPoint)velocity
              targetContentOffset:(inout CGPoint *)targetContentOffset {
#ifdef DEBUG
    NSLog ( @"MyViewController::scrollViewWillEndDragging:%@withVelocity:(%f,%f)targetContentOffset:(%f,%f)",scrollView,velocity.x, velocity.y, targetContentOffset->x, targetContentOffset->y );
#endif

    // We have to have had a "hard pull South" to trigger a refresh of the objects.
    if ( (velocity.y < 0) && ([scrollView contentOffset].y < -60) ) {
#ifdef DEBUG
        NSLog ( @"We will perform a new refresh." );
#endif
    }
}

The "-60" is because I'm looking for the best offset before I set it into a static.

Upvotes: 0

Tim Kokesh
Tim Kokesh

Reputation: 879

The totally native way to do it is to use a UITableViewController in your UIViewController, e.g.

{
    tableViewController = [[UITableViewController alloc] init];
    [tableViewController setTableView:myTableView];

    refreshControl = [[UIRefreshControl alloc] init];
    [tableViewController setRefreshControl:refreshControl];
    [refreshControl addTarget:self action:@selector(refresh:) forControlEvents:UIControlEventValueChanged];
}

Upvotes: 7

Ian MacDonald
Ian MacDonald

Reputation: 14030

If you add a UIScrollViewDelegate to your UITableView, you can respond to scrollViewDidScroll: events. A negative contentOffset.y value indicates that your user has pulled down at the top of your tableview.

Upvotes: 1

Related Questions