Preserve UITableView offset when inserting rows at the top with UITableViewAutomaticDimension
I have UITableView
s Autolayout
in my application. I need to insert some rows into my TableView after clicking the button LoadEarlier
to index [0],
but I want to stay at my last position of my TableView. (Download previously Like WhatsApp and ...).
My problem is that after installation the contentOffset
position of my TableVoew is not correct.
I check this link, but this problem is not similar to my problem, but I think the answer will help us. UITableViewAutomaticDimension - Cells move when table is reloaded and this link: Keep uitableview static when inserting rows at the top
I do like this:
// in ViewDidLoad
self.myTableView.estimatedRowHeight = 100;
self.myTableView.rowHeight = UITableViewAutomaticDimension;
//implemention of LoadEalier Method
CGFloat oldTableViewHeight = self.myTableView.contentSize.height;
for (int i = temp ; i < temp +26; i++) {
myObject * tempObject = [[myObject alloc]init];
tempObject.name = [NSString stringWithFormat:@"Obj : %d",i];
tempObject.uID = [[NSUUID UUID]UUIDString];
[_dataArray insertObject:tempObject atIndex:0];
}
[self.myTableView reloadData];
CGFloat newTableViewHeight = self.myTableView.contentSize.height;
self.myTableView.contentOffset = CGPointMake(0, self.myTableView.contentSize.height - oldTableViewHeight);
if i remove AutomaticDimension from my delegate and ... it works fine on static Cell height, but I need AutomaticDimension to calculate my cell height.
source to share
Update
I can't seem to find a solution for storing the UITableView
offset with UITableViewAutomaticDimension
.
i removed UITableViewAutomaticDimension
from heightForRowAtIndexPath
and estimateForRowAtIndexPath
and kept UITableView
:
CGFloat oldTableViewHeight = self.tableView.contentSize.height; // we keep current content offSet for revert to this position after Reload Table
// Update your Data
[self.tableView reloadData];
CGFloat finalYPostioton = self.tableView.contentSize.height - oldTableViewHeight - numberOfYourSection * sectionHeight;
finalYPostioton = finalYPostioton - spaceFromTopCell; // we need this for showing a little of top cell from our index. spaceFromTopCell -->10
[self.tableView setContentOffset:CGPointMake(0,finalYPostioton) animated:NO];
source to share