Created
July 5, 2018 08:12
-
-
Save victorchee/3827222ddc7a4265b233ecd650d833c0 to your computer and use it in GitHub Desktop.
Horizontal center scroll UICollectionView layout.
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
| import UIKit | |
| class HorizontalCenterScrollFlowLayout: UICollectionViewFlowLayout { | |
| override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint { | |
| var offsetAdjustment = CGFloat.greatestFiniteMagnitude | |
| let horizontalCenter = proposedContentOffset.x + collectionView!.bounds.width / 2.0 | |
| let targetRect = CGRect(x: proposedContentOffset.x, y: 0, width: collectionView!.bounds.width, height: collectionView!.bounds.height) | |
| if let attributes = super.layoutAttributesForElements(in: targetRect) { | |
| for attribute in attributes { | |
| let itemHorizontalCenter = attribute.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