Skip to content

Instantly share code, notes, and snippets.

@velyan
Created January 29, 2015 20:59
Show Gist options
  • Save velyan/33bca641ced413f027b4 to your computer and use it in GitHub Desktop.
Save velyan/33bca641ced413f027b4 to your computer and use it in GitHub Desktop.
CollectionViewFlowLayout Centered Cell
@interface YANCollectionViewFlowLayout : UICollectionViewFlowLayout
@property (nonatomic, assign) CGFloat previousOffset;
@property (nonatomic, assign) NSInteger currentPage;
@end
@implementation YANCollectionViewFlowLayout
- (void) setupInitialContentOffset {
self.previousOffset = self.collectionView.contentOffset.x;
self.currentPage = self.previousOffset / (self.itemSize.width + self.minimumInteritemSpacing);
CGFloat updatedOffset = (self.itemSize.width + self.minimumInteritemSpacing) * self.currentPage;
self.previousOffset = updatedOffset;
[self.collectionView setContentOffset:CGPointMake(updatedOffset, self.collectionView.contentOffset.y) animated:YES];
}
- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity {
NSInteger pageOffset = proposedContentOffset.x / (self.itemSize.width + self.minimumInteritemSpacing);
self.currentPage = pageOffset;
// Update offset by using item size + spacing
CGFloat updatedOffset = (self.itemSize.width + self.minimumInteritemSpacing) * self.currentPage;
self.previousOffset = updatedOffset;
return CGPointMake(updatedOffset, proposedContentOffset.y);
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment