点击“加载早期项目”button时,如何将UITableView的滚动位置设置为之前的位置

我有一个像iOS iMessage细节视图的tableView。 而且我还有一个button,在“加载早期消息”使用的tableView的顶部。

当我滚动tableView顶部,我的button出现,我点击button后,我填写早期的logging和重新加载tableView。

当logging在tableView中重新填充时,滚动位置不会更改。

顺便说一句,我试着保持滚动上一个位置值和setcontentoffset到前一个CGPoint 。 但是我意识到,当点击button时,scrollposition总是为0。 所以,我setcontentoffset后,滚动保持顶部..

我需要将scrollview的位置重新定位到之前的区域。

—编辑—

我试图改进我的方法,“保持scrollview的以前的位置”。

我find了解决scheme,效果很好。 我会分享所有的;

将此添加到.h文件: @property (nonatomic) CGFloat scrollsPreviousLocation;@synthesize scrollsPreviousLocation; 到.m文件。

现在,这是诀窍:我从底部计算滚动的位置..不是从顶部。

 - (void)scrollViewDidScroll:(UIScrollView *)scrollView { scrollsPreviousLocation = (self.tableView.contentSize.height - scrollView.contentOffset.y); } 

在计算过程之后,现在我需要将内容偏移设置到之前的位置;

 [tableView reloadData]; CGPoint offset = CGPointMake(0,tableView.contentSize.height - scrollsPreviousLocation); [tableView setContentOffset:offset animated:NO]; 

在加载之前的内容之前,当您位于表格视图之上时, contentOffset值为0。 如果您希望能够在上面的消息行重新加载表视图之后保持在相同的滚动位置,则必须执行以下操作:

 // Save the contentSize of your table view before reloading it CGFloat oldTableViewHeight = self.tableView.contentSize.height; // Reload your table view with your new messages // Put your scroll position to where it was before CGFloat newTableViewHeight = self.tableView.contentSize.height; self.tableView.contentOffset = CGPointMake(0, newTableViewHeight - oldTableViewHeight); 

而已 !

如果你以前的表格视图的内容大小高度是10,而新的是19,那么你想把你的内容偏移量设置为9(等于从重新加载之前的10开始),等于19-10。

从@Kevin Hirsch的工作,但在自动布局模式下,请记住添加tableView.layoutIfNeeded(),否则你会得到估计的高度。 这里是我的代码在迅速:

 // Save the contentSize of your table view before reloading it let oldTableViewHeight = self.tableView.contentSize.height // Reload your table view with your new messages self.tableView.layoutIfNeed() // Put your scroll position to where it was before let newTableViewHeight = self.tableView.contentSize.height; self.tableView.contentOffset = CGPointMake(0, newTableViewHeight - oldTableViewHeight);