How to select item/cell of UICollectionView from code
Solution 1
I am calling [self collectionView:yourView didSelectItemAtIndexPath:yourIndexPath]
to programmatically select a cell. But in the method cell is always nil. This works perfectly well when user selects a cell.
Solution 2
Yes, this is proper behaviour. Documentation for [selectItemAtIndexPath:animated:scrollPosition:]
says:
This method does not cause any selection-related delegate methods to be called.
Solution 3
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 :-)
Nikola Kirev
I study Software Engineering at the Sofia University, Bulgaria.
Updated on March 04, 2020Comments
-
Nikola Kirev about 4 years
I have implemented a
UICollectionView
in my app. My problem is that I need to select (like if the user tapped on it) a cellprogrammatically
. The method:- (void)selectItemAtIndexPath:(NSIndexPath *)indexPath animated:(BOOL)animated scrollPosition:(UICollectionViewScrollPosition)scrollPosition
That is part of the
UICollectionView
class is not what i need to call, since this method does not call:- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
It just sets the
selected
property of the cell toYES
;