Skip to content
This repository has been archived by the owner on Aug 14, 2019. It is now read-only.

How maintain scroll position? #441

Closed
educosta opened this issue Aug 15, 2014 · 8 comments
Closed

How maintain scroll position? #441

educosta opened this issue Aug 15, 2014 · 8 comments

Comments

@educosta
Copy link

How can I still scroll position when I load new messages?

If disabled automaticallyScrollsToMostRecentMessage scroll to up, if enabled scroll to down.

Thank you

@dim0v
Copy link
Contributor

dim0v commented Aug 18, 2014

Hi, @educosta!
You can use UIScrollView contentOffset and contentSize properties.

Before loading a new bunch of messages save your current y-offset (but counting from the bottom, not from the top). I.e.

CGFloat oldOffset = self.collectionView.contentSize.height - self.collectionView.contentOffset.y

After that, load new messages to dataSource, call [self.collectionView reloadData] and [self.collectionView layoutIfNeeded] and set collectionView's contentOffset to the one you've previously saved (remember that it's "reversed"):

self.collectionView.contentOffset = CGPointMake(0.0, self.collectionView.contentSize.height - oldOffset);

@jessesquires
Copy link
Owner

thanks for the answer @dim0v!

@educosta
Copy link
Author

Hi @dim0v

Works for you? I tried on demo project but not works :(

@dim0v
Copy link
Contributor

dim0v commented Aug 18, 2014

Here is the code I am using in my current project (a bit simplified and cleared from unrelated things). It works fine.

- (void) loadHistory {
    CGFloat oldOffsetReversed = self.collectionView.contentSize.height - self.collectionView.contentOffset.y;

    NSUInteger pageSize = [self fetchNextPage]; //reloadData is called inside
    [self.view layoutIfNeeded];

    CGFloat offset = self.collectionView.contentSize.height - oldOffsetReversed;

    self.collectionView.contentOffset = CGPointMake(self.collectionView.contentOffset.x, offset);
}

@dim0v
Copy link
Contributor

dim0v commented Aug 18, 2014

Also, if message loading is asynchronous, this should be done inside the completion handler.

If still doesn't work for you, please, post your code somwhere, i'll try to figure out why :)

Btw, I assumed you are loading messages on the top. If new messages are added to the bottom, then setting automaticallyScrollsToMostRecentMessage to NO should be enough to preserve scroll position.

@educosta
Copy link
Author

Hi @dim0v

Now works, I missing [self.view layoutIfNeeded]; after reload

You're the best!

@mitchellporter
Copy link

@dim0v works perfectly even on iOS 9 ;)

@bpisano
Copy link

bpisano commented Apr 16, 2018

I have this issue too and I've tried the layoutIfNeeded. But with a lot of cells and self sizing, it completely freeze the UI.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

5 participants