Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 444
IkegawaTaro Avatar asked Mar 16 '13 02:03

IkegawaTaro


1 Answers

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
like image 95
Shamsudheen TK Avatar answered Oct 23 '22 20:10

Shamsudheen TK