I have a Collection View that can show about 3.5 cells at a time, and I want it to be paging-enabled. But I'd like it to snap to each cell (just like the App Store app does), and not scroll the full width of the view. How can I do that?
Another way is to create a custom UICollectionViewFlowLayout and override the method like so:
- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)offset withScrollingVelocity:(CGPoint)velocity { CGRect cvBounds = self.collectionView.bounds; CGFloat halfWidth = cvBounds.size.width * 0.5f; CGFloat proposedContentOffsetCenterX = offset.x + halfWidth; NSArray* attributesArray = [self layoutAttributesForElementsInRect:cvBounds]; UICollectionViewLayoutAttributes* candidateAttributes; for (UICollectionViewLayoutAttributes* attributes in attributesArray) { // == 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 - halfWidth, offset.y); }
If you are looking for a Swift solution, check out this Gist
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With