0

I am implementing a UICollectionView which shows only a single line of cells. It is like an image cover flow. This means I have subclassed UICollectionViewFlowLayout. My implementation works fine when I use my finger for scrolling, meaning that the following delegate method is called and I center the cell;

-(CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity

However when the view loads I want the view to automatically scroll to a cell. For this automatic scroll I use the following;

[self.CollectionView scrollToItemAtIndexPath:_selectedIndexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];

The problem is that targetContentOffsetForProposedContentOffset is not called and thus when the automatic scroll is complete the cell is off the centre.

So how can I programmatically scroll my collection view so that it will also centre on the cell being scrolled to?

darbid
  • 2,545
  • 23
  • 55

1 Answers1

5

Solved this issue myself.

According to the book "iOS UICollectionView The Complete Guide" (Listing 6.7) scrollToItemAtIndexPath: cannot be used in this cover flow type layout as it will not centre the cell.

I have posted below the way it is suggested in the book. Based on the indexPath you want to have you need to calculate the offset of the collection view yourself, and then use the targetContentOffsetForProposedContentOffset: to automatically centre it for you.

CGPoint proposedOffset = CGPointMake(0, 0);

proposedOffset.x = _selectedIndexPath.item * (flow.itemSize.width + flow.minimumLineSpacing);

CGPoint contentOffset = [flow targetContentOffsetForProposedContentOffset:proposedOffset withScrollingVelocity:CGPointMake(0, 0)];

[self.statCollectionView setContentOffset:contentOffset animated:YES];
darbid
  • 2,545
  • 23
  • 55