Created
March 20, 2015 13:19
-
-
Save ardarda/568146c4f1883f118579 to your computer and use it in GitHub Desktop.
collection view auto snap center with custom width
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 | |
{ | |
CGFloat offSetAdjustment = MAXFLOAT; | |
CGFloat horizontalCenter = (CGFloat) (proposedContentOffset.x + (self.collectionView.bounds.size.width / 2.0)); | |
CGRect targetRect = CGRectMake(proposedContentOffset.x, 0.0, self.collectionView.bounds.size.width, self.collectionView.bounds.size.height); | |
NSArray *array = [self layoutAttributesForElementsInRect:targetRect]; | |
UICollectionViewLayoutAttributes *currentAttributes; | |
for (UICollectionViewLayoutAttributes *layoutAttributes in array) | |
{ | |
if(layoutAttributes.representedElementCategory == UICollectionElementCategoryCell) | |
{ | |
CGFloat itemHorizontalCenter = layoutAttributes.center.x; | |
if (ABS(itemHorizontalCenter - horizontalCenter) < ABS(offSetAdjustment)) | |
{ | |
currentAttributes = layoutAttributes; | |
offSetAdjustment = itemHorizontalCenter - horizontalCenter; | |
} | |
} | |
} | |
CGFloat nextOffset = proposedContentOffset.x + offSetAdjustment; | |
proposedContentOffset.x = nextOffset; | |
CGFloat deltaX = proposedContentOffset.x - self.collectionView.contentOffset.x; | |
CGFloat velX = velocity.x; | |
// detection form gist.github.com/rkeniger/7687301 | |
// based on http://stackoverflow.com/a/14291208/740949 | |
if(deltaX == 0.0 || velX == 0 || (velX > 0.0 && deltaX > 0.0) || (velX < 0.0 && deltaX < 0.0)) { | |
} else if(velocity.x > 0.0) { | |
for (UICollectionViewLayoutAttributes *layoutAttributes in array) | |
{ | |
if(layoutAttributes.representedElementCategory == UICollectionElementCategoryCell) | |
{ | |
CGFloat itemHorizontalCenter = layoutAttributes.center.x; | |
if (itemHorizontalCenter > proposedContentOffset.x) { | |
proposedContentOffset.x = nextOffset + (currentAttributes.frame.size.width / 2) + (layoutAttributes.frame.size.width / 2); | |
break; | |
} | |
} | |
} | |
} else if(velocity.x < 0.0) { | |
for (UICollectionViewLayoutAttributes *layoutAttributes in array) | |
{ | |
if(layoutAttributes.representedElementCategory == UICollectionElementCategoryCell) | |
{ | |
CGFloat itemHorizontalCenter = layoutAttributes.center.x; | |
if (itemHorizontalCenter > proposedContentOffset.x) { | |
proposedContentOffset.x = nextOffset - ((currentAttributes.frame.size.width / 2) + (layoutAttributes.frame.size.width / 2)); | |
break; | |
} | |
} | |
} | |
} | |
proposedContentOffset.y = 0.0; | |
return proposedContentOffset; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment