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 ??
try to replace
reloadData
withtableView.reloadRows
(at: tableView!.indexPathsForVisibleRows!, with: .none
),but you should be care about
no cells
, ifno cells
, this method should cause crash.When you want to reload you have to
and also use this
UITableViewDelegate
and your tableView will remain on the previous scroll position without scrolling
I am showing if only one row is being added. You can extend it to multiple rows.
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.For Swift 3+:
You need to save the current offset of the
UITableView
, then reload and then set the offset back on theUITableView
.I have created this function for this purpose:
Simply call it with:
reload(tableView: self.tableView)
I'm doing it this way:
...also, since I use dynamic cell height, to avoid some weirdness, the estimation is cached:
Just set
estimatedRowHeight
to maximum possible value.That's it!!
Note:
Please do not use
FLT_MAX, DBL_MAX
value. May be it will crash your app.