Forked from mmick66/UICollectionViewFlowLayoutCenterItem.m
Last active
August 29, 2015 14:04
-
-
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
This file contains 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 | |
{ | |
// 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