How to select a UICollectionView item / cell from code

I applied UICollectionView in my application. My problem is that I need to select (for example, if the user clicked on it) a cell programmatically . Method:

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

This is part of the UICollectionView class - this is not what I need to call, since this method does not call:

 - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath 

It simply sets the selected property of the cell to YES ;

+6
source share
3 answers

I call [self collectionView:yourView didSelectItemAtIndexPath:yourIndexPath] to programmatically select the cell. But in the method, the cell is always zero. This works fine when the user selects a cell.

+7
source

Yes, this is the correct behavior. The documentation for [selectItemAtIndexPath:animated:scrollPosition:] says :

This method does not call any delegation methods associated with the selection. be called.

+8
source

First you need to make the target cell visible, otherwise [yourCollectionView cellForItemAtIndexPath:yourIndexPath] always returns nil.

 // scroll to the cell [yourCollectionView scrollToItemAtIndexPath:yourIndexPath atScrollPosition:UICollectionViewScrollPositionBottom animated:NO]; // call delegate method [self collectionView:yourCollectionView didSelectItemAtIndexPath:yourIndexPath]; // now you have selected the cell and can do anything to it in the delegate method :-) 
+7
source

All Articles