Created
February 28, 2015 18:27
-
-
Save benjaminsnorris/9a6402670ed0e5576c8f to your computer and use it in GitHub Desktop.
Scroll collection view to always have cell centered in 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
- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity { | |
CGFloat offsetAdjustment = MAXFLOAT; | |
CGFloat horizontalCenter = proposedContentOffset.x + (CGRectGetWidth(self.collectionView.bounds) / 2.0); | |
CGRect targetRect = CGRectMake(proposedContentOffset.x, 0.0, self.collectionView.bounds.size.width, self.collectionView.bounds.size.height); | |
NSArray *attributesArray = [super layoutAttributesForElementsInRect:targetRect]; | |
for (UICollectionViewLayoutAttributes *layoutAttributes in attributesArray) { | |
CGFloat itemHorizontalCenter = layoutAttributes.center.x; | |
if (ABS(itemHorizontalCenter - horizontalCenter) < ABS(offsetAdjustment)) { | |
offsetAdjustment = itemHorizontalCenter - horizontalCenter; | |
} | |
} | |
return CGPointMake(proposedContentOffset.x + offsetAdjustment, proposedContentOffset.y); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment