Last active
January 7, 2021 23:47
-
-
Save eoghain/ccc2b8d1e365582963d15476bfd706f3 to your computer and use it in GitHub Desktop.
/// Snaps nearest cell to center of collection view
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
final class SingleItemCarouselFlowLayout: UICollectionViewFlowLayout { | |
override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint { | |
guard let collectionView = collectionView else { | |
return super.targetContentOffset(forProposedContentOffset: proposedContentOffset, withScrollingVelocity: velocity) | |
} | |
var offsetAdjustment: CGFloat = .greatestFiniteMagnitude | |
let horizontalCenter = proposedContentOffset.x + (collectionView.bounds.width / 2) | |
let targetRect = CGRect(x: proposedContentOffset.x, y: 0.0, width: collectionView.bounds.width, height: collectionView.bounds.height) | |
super.layoutAttributesForElements(in: targetRect)?.forEach{ layoutAttributes in | |
let itemHorizontalCenter = layoutAttributes.center.x | |
if abs(itemHorizontalCenter - horizontalCenter) < abs(offsetAdjustment) { | |
offsetAdjustment = itemHorizontalCenter - horizontalCenter | |
} | |
} | |
return CGPoint(x: proposedContentOffset.x + offsetAdjustment, y: proposedContentOffset.y) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment