Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UICollectionView with paging - setting page width

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?

like image 715
Guilherme Avatar asked Dec 10 '13 14:12

Guilherme


1 Answers

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

  • note: this will work when we are really showing preview cells (even if they have an alpha of 0.0f). This is because if the preview cells are not available at the time of scrolling their attributes object will not be passed in the loop...
like image 155
Mike M Avatar answered Oct 08 '22 12:10

Mike M