4

I have a UICollectionView, horizontal scrolling, paging=YES, displaying three cells per page. In the event its datasource has four items, the collectionView will have "two pages".

Strangely, upon tapping on cells, the collectionView always snaps back to contentOffset(0,0). See the video here: https://www.dropbox.com/s/vlqt3mh7bwyeiw7/collectionviewbug.mov?dl=0

Doing nothing fancy, check the code on my git repo: https://github.com/opfeffer/collectionviewbug

Anybody have an idea what causes this issue and how to prevent it? Thanks!!

opfeffer
  • 593
  • 4
  • 16

1 Answers1

1

This is happening because say your page size is 3, but with 4 elements you are showing 2/3 of the first page and 1/3 of a expected 2nd page. When you tap in the cell the collection move to show completely the page that has more content shown to the user at that moment.

You can check this if for example you use 7 elements and press on the 7th the collection go to the 4th.

The way to avoid this behaviour would be to have have always "complete pages" so if you don't have enough elements to fill the page you need to tell the content view to be bigger anyway. So you need to subclass UICOllectionViewFlowLayout with something similar to this:

  • (CGSize)collectionViewContentSize { CGSize contentSize = [super collectionViewContentSize]; // This assume you have a public method in your collection view controller to calculate the number of pages for any given number of elements NSInteger pages = [(YourCollectionViewController *) self.collectionView.delegate pagesNumber]; // then you return the size for n times the number of pages in width and one time for height return CGSizeMake(CGRectGetWidth(self.collectionView.frame) * pages, contentSize.height); }