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
?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With