Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Air-Craft/c9771c19ed9a2b6b734a to your computer and use it in GitHub Desktop.
Save Air-Craft/c9771c19ed9a2b6b734a to your computer and use it in GitHub Desktop.
Make UICollectionViewFlowLayout handle page sizes that are less than the width. #ios #UICollectionView #scrolling #carousel
- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity
{
// We're going to center the centermost item...
// Use the bounds to have the snap happen the minute drag stops. In other words use the current content offset (which = bounds.origin) instead of the proposed end offset (which takes velocity into account)
CGRect proposedRect = self.collectionView.bounds;
CGFloat proposedContentOffsetCenterX = proposedContentOffset.x + self.collectionView.bounds.size.width * 0.5f;
// Comment out if you want the collectionview simply stop at the center of an item while scrolling freely (ie take velocity into account)
// CGSize collectionViewSize = self.collectionView.bounds.size;
// proposedRect = CGRectMake(proposedContentOffset.x, 0.0, collectionViewSize.width, collectionViewSize.height);
// Find the attribute/cell, in the relevant visible rect which is closest to the proposed offeset. Why proposed? B/c this is a clever trick to ensure we round to the cell towards the direction of the scroll.
UICollectionViewLayoutAttributes* candidateAttributes;
// Find the attribute/cell which is
for (UICollectionViewLayoutAttributes* attributes in [self layoutAttributesForElementsInRect:proposedRect])
{
// == Skip comparison with non-cell items (headers and footers) == //
if (attributes.representedElementCategory != UICollectionElementCategoryCell)
{
continue;
}
// == First time in the loop == //
if(!candidateAttributes)
{
candidateAttributes = attributes;
continue;
}
if (fabsf(attributes.center.x - proposedContentOffsetCenterX) < fabsf(candidateAttributes.center.x - proposedContentOffsetCenterX))
{
candidateAttributes = attributes;
}
}
return CGPointMake(candidateAttributes.center.x - self.collectionView.bounds.size.width * 0.5f, proposedContentOffset.y);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment