How to select item in collectionview programmatically?

mrd picture mrd · Feb 8, 2014 · Viewed 53k times · Source

I have a UICollectionView. The UICollectionView's datasource is a NSArray of students (from CoreData). I want the current student item be selected/highlighted.

How can I do this? I know there is a method:

- (void)selectItemAtIndexPath:(NSIndexPath *)indexPath 
                     animated:(BOOL)animated 
               scrollPosition:(UICollectionViewScrollPosition)scrollPosition;

which takes as arguments an NSIndexPath and UICollectionViewScrollPosition.

I have the datasource (NSArray of students populated from CoreData) and the student object to be selected.

So, how do I get the NSIndexPath and UICollectionViewScrollPosition? Or is there any other way to highlight an item?

Answer

Shahin picture Shahin · Feb 8, 2014

You can simply use this after [self.collectionView reloadData]

[self.collectionView 
   selectItemAtIndexPath:[NSIndexPath indexPathForItem:index inSection:0] 
                animated:YES
          scrollPosition:UICollectionViewScrollPositionCenteredVertically];

where index is the index number for the selected student.