4

I am implementing a UICollectionView in my iOS app. I have it so each cell is the width of the screen and I want to have it so when scrolling horizontally it locks onto the visible cell and moves it to the center of the screen. The code bellow I have only works for the first cell. I don't understand how to get this to work for any cell the user has visible.

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    int index  = 0;
    for (TextCell * t in [_tabBarCollectionView visibleCells]) {
        if ((t.center.x>0)&&(t.center.x<[[UIScreen mainScreen]bounds].size.width)) {
            [_tabBarCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
            break;
        }
        index++;
    }

}
BDGapps
  • 3,120
  • 8
  • 50
  • 73

1 Answers1

4

You can turn paging on for the collection view and it will have that effect. Go to the xib file or storyboard that has the collection added and enable paging under its properties.

Kris Gellci
  • 8,943
  • 5
  • 35
  • 47
  • OK great but how do I detect what index is visible? – BDGapps Apr 27 '13 at 19:58
  • call this method in scrollview did end decelerating, if you have paging on and you say that the cell is the size of the screen, there will only be one position returned: - (NSArray *)indexPathsForVisibleItems Edit: so do [_tabBarCollectionView indexPathsForVisibleItems]; – Kris Gellci Apr 27 '13 at 20:08
  • ok but I have 2 collectionViews so how do I detect which collection view it is talking about – BDGapps Apr 27 '13 at 20:24
  • The scroll view that is being passed into the scroll view did end decelerating method will be the collection view, so you can check is scroll view == collection view or scroll view == collection view 2. – Kris Gellci Apr 27 '13 at 21:38
  • 1
    As u said previously the indexPathsForVisibleItems should be returning only 1 as the collection view width is 320 and the cell width is 320 but it's returning 2 – BDGapps Apr 28 '13 at 15:57
  • Although is a little old, this post might help those looking how to solve this issue. http://stackoverflow.com/a/24396643/3708095 – jdev Apr 17 '15 at 05:18