Created
August 15, 2018 02:33
-
-
Save sean7218/c6bd0ed9d4ffeac36617de79bbbe0afb to your computer and use it in GitHub Desktop.
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
class SnappingCollectionViewLayout: 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 horizontalOffset = proposedContentOffset.x + collectionView.contentInset.left | |
let targetRect = CGRect(x: proposedContentOffset.x, y: 0, width: collectionView.bounds.size.width, height: collectionView.bounds.size.height) | |
let layoutAttributesArray = super.layoutAttributesForElements(in: targetRect) | |
layoutAttributesArray?.forEach({ (layoutAttributes) in | |
let itemOffset = layoutAttributes.frame.origin.x | |
if fabsf(Float(itemOffset - horizontalOffset)) < fabsf(Float(offsetAdjustment)) { | |
offsetAdjustment = itemOffset - horizontalOffset | |
} | |
}) | |
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