Skip to content

Instantly share code, notes, and snippets.

@xmollv
Created February 1, 2019 16:25
Show Gist options
  • Save xmollv/a8ffc523e175e009c9de500255bf878b to your computer and use it in GitHub Desktop.
Save xmollv/a8ffc523e175e009c9de500255bf878b to your computer and use it in GitHub Desktop.
/// Source: https://bitbucket.org/mmick66/centercellpagingcollectionview
class CenterCellCollectionViewFlowLayout: UICollectionViewFlowLayout {
var mostRecentOffset = CGPoint()
override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
guard let collectionView = self.collectionView else {
self.mostRecentOffset = super.targetContentOffset(forProposedContentOffset: proposedContentOffset)
return self.mostRecentOffset
}
guard velocity.x != 0 else {
return self.mostRecentOffset
}
if(proposedContentOffset.x == -(collectionView.contentInset.left)) {
return proposedContentOffset
}
let cvBounds = collectionView.bounds
let halfWidth = cvBounds.size.width * 0.5
guard let attributesForVisibleCells = self.layoutAttributesForElements(in: cvBounds) else {
self.mostRecentOffset = super.targetContentOffset(forProposedContentOffset: proposedContentOffset)
return self.mostRecentOffset
}
var candidateAttributes: UICollectionViewLayoutAttributes?
for attributes in attributesForVisibleCells where attributes.representedElementCategory == .cell {
if (attributes.center.x == 0) || (attributes.center.x > (collectionView.contentOffset.x + halfWidth) && velocity.x < 0) {
continue
}
candidateAttributes = attributes
}
guard let validAttributes = candidateAttributes else {
return self.mostRecentOffset
}
self.mostRecentOffset = CGPoint(x: floor(validAttributes.center.x - halfWidth), y: proposedContentOffset.y)
return self.mostRecentOffset
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment