Programmatically setting a UICollectionViewCell as Selected but indexPathsForSelectedItems.count is 0

ios, objective-c, uicollectionview, uicollectionviewcell

Solution

Here is the answer.

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

Example Code:

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);
}

OutPut

selected count 1

Problem

I programmatically set a custom `UICollectionViewCell` called `CheckCell` to be selected 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" leading me to believe the cell at `IndexPath` is indeed selected. However, the result of the second NSLog is 0. Why is the selected cell's index not being added to `indexPathsForSelectedItems`?

Original source