Skip to content

Instantly share code, notes, and snippets.

@muukii
Last active September 2, 2018 08:13
Show Gist options
  • Save muukii/29249c295a0f2c4fecde61d99abc94f5 to your computer and use it in GitHub Desktop.
Save muukii/29249c295a0f2c4fecde61d99abc94f5 to your computer and use it in GitHub Desktop.
import UIKit
final class KeepingContentOffsetCollectionViewLayout : UICollectionViewFlowLayout {
private var oldOffset: CGFloat?
typealias Completion = () -> Void
/// Perform passed closure with keeping current contentOffset.
///
/// - Parameter closure: You should call completion closure when operation completed.
func performWithKeepingContentOffset(_ closure: (@escaping Completion) -> Void) {
guard let collectionView = self.collectionView else { return }
let oldOffsetY = collectionViewContentSize.height - collectionView.contentOffset.y
performWithKeeping(contentOffsetY: oldOffsetY, closure)
}
func performWithKeeping(contentOffsetY: CGFloat, _ closure: (@escaping Completion) -> Void) {
assert(oldOffset == nil, "Completion did not be called last time")
oldOffset = contentOffsetY
closure({
self.oldOffset = nil
})
}
override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
guard let oldOffset = oldOffset else {
return proposedContentOffset
}
var offset = proposedContentOffset
offset.y = collectionViewContentSize.height - oldOffset
return offset
}
override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
return proposedContentOffset
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment