Skip to content

Instantly share code, notes, and snippets.

@benjaminsnorris
Created February 28, 2015 18:27
Show Gist options
  • Save benjaminsnorris/9a6402670ed0e5576c8f to your computer and use it in GitHub Desktop.
Save benjaminsnorris/9a6402670ed0e5576c8f to your computer and use it in GitHub Desktop.
Scroll collection view to always have cell centered in view
- (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