Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITableView Refresh without scrolling

I have a _TableView with items , and I want to set automatic refresh,and I don't want it to scroll on refresh , lets say user scrolled 2 pages down , and the refresh trigered -> so I want to put the refreshed content to the top of the table without interupting user's scrolling

Assume user was on row 18 and now the _dataSource is refreshed so it fetched lets say 4 items , so I want user to stay on the item he was.

What would be the best approach to achieve it ??

like image 330
ColdSteel Avatar asked Aug 31 '14 06:08

ColdSteel


3 Answers

For Swift 3+:

You need to save the current offset of the UITableView, then reload and then set the offset back on the UITableView.

I have created this function for this purpose:

func reload(tableView: UITableView) {

    let contentOffset = tableView.contentOffset
    tableView.reloadData()
    tableView.layoutIfNeeded()
    tableView.setContentOffset(contentOffset, animated: false)

}

Simply call it with: reload(tableView: self.tableView)

like image 112
David Seek Avatar answered Oct 18 '22 04:10

David Seek


SWIFT 3

let contentOffset = self.tableView.contentOffset
self.tableView.reloadData()
self.tableView.layoutIfNeeded()
self.tableView.setContentOffset(contentOffset, animated: false)

This is error of iOS8 when using UITableViewAutomatic Dimension. We need store the content offset of table, reload table, force layout and set contenOffset back.

CGPoint contentOffset = self.tableView.contentOffset;
[self.tableView reloadData];
[self.tableView layoutIfNeeded];
[self.tableView setContentOffset:contentOffset];
like image 33
Trung Phan Avatar answered Oct 18 '22 04:10

Trung Phan


I am showing if only one row is being added. You can extend it to multiple rows.

    // dataArray is your data Source object
    [dataArray insertObject:name atIndex:0];
    CGPoint contentOffset = self.tableView.contentOffset;
    contentOffset.y += [self tableView:self.tableView heightForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    [self.tableView reloadData];
    [self.tableView setContentOffset:contentOffset];

But for this to work you need to have defined - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath the method. Or else, you can directly give your tableview row height if it is constant.

like image 11
Prasad Avatar answered Oct 18 '22 04:10

Prasad