Skip to content

Instantly share code, notes, and snippets.

@pionl
Created September 4, 2014 09:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pionl/432fc8059dee3b540e38 to your computer and use it in GitHub Desktop.
Save pionl/432fc8059dee3b540e38 to your computer and use it in GitHub Desktop.
First cell starts in center of the view.
- (CGSize)collectionViewContentSize {
CGSize contentSize = [super collectionViewContentSize];
// we need to center last view
int items = [[self collectionView] numberOfItemsInSection:0];
UICollectionViewLayoutAttributes* layoutAttribute = (UICollectionViewLayoutAttributes*)[super layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForItem:items-1 inSection:0]];
float startX = contentSize.width - self.collectionView.bounds.size.width + self.collectionView.bounds.size.width / 2;
startX = layoutAttribute.frame.origin.x - startX;
startX += layoutAttribute.size.width / 2;
contentSize.width += startX;
layoutAttribute = (UICollectionViewLayoutAttributes*)[super layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0]];
[[self collectionView] setContentInset:UIEdgeInsetsMake(0, self.collectionView.bounds.size.width / 2 - layoutAttribute.frame.size.width / 2, 0, 0)];
return contentSize;
}
@ybeapps
Copy link

ybeapps commented Jan 10, 2018

This works for me (for a known size):

let halfScreen = CGSize(width: {Put here your full size - I use UIScreen.main.bounds.size.width} / 2 - 30 / 2, height: {Your height})
flowLayout.headerReferenceSize = halfScreen
flowLayout.footerReferenceSize = halfScreen

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment