Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select item in collectionview programmatically?

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?

like image 611
mrd Avatar asked Sep 05 '25 00:09

mrd


1 Answers

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.

like image 83
Shahin Avatar answered Sep 07 '25 21:09

Shahin