Programmatically setting the UICollectionViewCell as Selected, and indexPathsForSelectedItems.count is 0

I programmatically set a custom UICollectionViewCell called CheckCell as follows:

 [self.myCollectionView cellForItemAtIndexPath:indexPath] setSelected:YES]; if ([[self.myCollectionView cellForItemAtIndexPath:indexPath] isSelected]) { NSLog(@"Selected"); } NSLog(@"%i",[self.myCollectionView indexPathsForSelectedItems].count); 

The first NSLog prints "Selected," making me believe that the cell in IndexPath indeed selected. However, the result of the second NSLog is 0. Why is the selected cell index not added to indexPathsForSelectedItems ?

+4
source share
1 answer

Here's the answer.

Call selectItemAtIndexPath instead of [self.myCollectionView cellForItemAtIndexPath:indexPath] setSelected:YES];

Code example:

 NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0] ; [self.collectionView selectItemAtIndexPath:indexPath animated:YES scrollPosition:UICollectionViewScrollPositionNone]; if ([[self.collectionView cellForItemAtIndexPath:indexPath] isSelected]) { NSLog(@"selected count %i",[self.collectionView indexPathsForSelectedItems].count); } 

audio output

 selected count 1 
+8
source