user3852132 user3852132 - 1 year ago 92
Objective-C Question

how to set UITableView's scroll position to previous location when click "load earlier items" button

I have a tableView like iOS

detail view. And also I've a button at the top of tableView which used by "load earlier messages".

When I scrolled tableView to top, my button appears and after I clicked the button, I fill earlier records and reload tableView.

While the records are repopulating in tableView, scrolls position does not change.

By the way, I tried to keep scroll previous position value and
to previous
. But I realized that the scrollposition always be 0 when I clicked button. So, after I setcontentoffset, scroll stays the top..

I need to relocate scrollview's position to previous area.

--- Edit ---

I try to improve my method which "keeping previous location of scrollview".

And I found the solution and works great. I'll share for all;

add this to .h file:
@property (nonatomic) CGFloat scrollsPreviousLocation;

@synthesize scrollsPreviousLocation;
to .m file.

Now, Here is the trick: I calculate the position of scroll from bottom.. Not from Top.

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

After the calculation process, Now I need to set content offset to previous location;

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

Answer Source

When you are on top of your table view before loading previous content, you are at 0 for contentOffset. If you want to be able to stay at the same scroll position after reloading the table view with previous messages row above, you will have to do this :

// 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);

That's it !

If your previous table view content size height was 10 and the new one was 19, you want to place your content offset to 9 (so 10 from the bottom like before the reloading) which is equal to 19 - 10.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download