Reputation: 3563
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
?
Upvotes: 5
Views: 7515
Reputation: 31311
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
Upvotes: 8