Skip to content

Commit

Permalink
Do not restore content offset after scrolling to the bottom initially
Browse files Browse the repository at this point in the history
  • Loading branch information
evsaev committed Jun 3, 2021
1 parent 6c2aa2d commit af04d1e
Showing 1 changed file with 12 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -84,11 +84,15 @@ open class ChatMessageListCollectionViewLayout: UICollectionViewLayout {

/// As we very often need to preserve scroll offset after performBatchUpdates, the simplest solution is to save original
/// contentOffset and set it when batch updates end
open var restoreOffset: CGFloat?
private var restoreOffset: CGFloat?

/// Flag to make sure the `prepare()` function is only executed when the collection view had been loaded.
/// The rest of the updates should come from `prepare(forCollectionViewUpdates:)`.
private var didPerformInitialLayout = false

/// When `true` the `restoreOffset` is returned from `targetContentOffset(forProposedContentOffset:)`
/// which scrolls the message list to the bottom.
private var didPerformInitialScrollToBottom = false

// MARK: - Initialization

Expand Down Expand Up @@ -259,8 +263,13 @@ open class ChatMessageListCollectionViewLayout: UICollectionViewLayout {
override open func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
guard let collectionView = self.collectionView else { return proposedContentOffset }
// if we have any content offset to restore and if the collection view has enough items to scroll, restore it
if let restore = restoreOffset, collectionView.contentSize.height > collectionView.bounds.height {
return CGPoint(x: 0, y: collectionViewContentSize.height - restore)
if let restore = restoreOffset,
collectionView.contentSize.height > collectionView.bounds.height,
!didPerformInitialScrollToBottom {
let offset = CGPoint(x: 0, y: collectionViewContentSize.height - restore)
print("targetContentOffset(forProposedContentOffset) will restore \(offset)")
didPerformInitialScrollToBottom = true
return offset
}
return proposedContentOffset
}
Expand Down

0 comments on commit af04d1e

Please sign in to comment.