UITableView and UIRefreshControl

gabac picture gabac · Oct 1, 2012 · Viewed 20.1k times · Source

I'm trying to move the UIRefreshControl on top of my headerView or at least getting it to work with the contentInset. Anyone know how to use it?

I used a headerView to have a nice background when scrolling within the TableView. I wanted to have a scrollable background.

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// Set up the edit and add buttons.

self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
self.tableView.backgroundColor = [UIColor clearColor];

[self setWantsFullScreenLayout:YES];

self.tableView.contentInset = UIEdgeInsetsMake(-420, 0, -420, 0);

UIImageView *top = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"top.jpg"]];
self.tableView.tableHeaderView = top;

UIImageView *bottom = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bottom.jpg"]];
self.tableView.tableFooterView = bottom;

UIBarButtonItem *leftButton = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"settingsIcon"] style:UIBarButtonItemStylePlain target:self action:@selector(showSettings)];
self.navigationItem.leftBarButtonItem = leftButton;

UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addList)];
self.navigationItem.rightBarButtonItem = addButton;

//Refresh Controls
self.refreshControl = [[UIRefreshControl alloc] init];

[self.refreshControl addTarget:self action:@selector(refreshInvoked:forState:) forControlEvents:UIControlEventValueChanged];
}

Answer

Echelon picture Echelon · Oct 16, 2012

I'm not really sure what your intention is with the contentInset stuff, but in terms of adding a UIRefreshControl to a UITableView, it can be done. UIRefreshControl is actually intended for use with UITableViewController, but if you just add it as a subview to a UITableView it magically works. Please note this is undocumented behaviour, and may not be supported in another iOS release, but it is legal since it uses no private APIs.

- (void)viewDidLoad
{
    ...
    UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
    [refreshControl addTarget:self action:@selector(handleRefresh:) forControlEvents:UIControlEventValueChanged];
    [self.myTableView addSubview:refreshControl];
}

- (void)handleRefresh:(id)sender
{
    // do your refresh here...
}

Credit to @Keller for noticing this.