Reputation: 5180
I am trying to make a collection view show multiple selections by adding a badge in each cell view. It sets the initial (unselected) image correctly, but the view is never updated to the selected version. I've tried setting it manually, so I know the selected image works and is visible in the cell. The NSLog shows 'selected' is toggling as expected and breakpoints show that the appropriate assignment to the image is being executed. Excuse the indention, SO won't play nicely and it's after midnight.
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
SMListCollectionViewCell *cell = (SMListCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
if ( !indexPath.row )
{
cell.image.image = [UIImage imageNamed:@"Add"];
cell.label.text = @"Create New";
cell.imageBadge.hidden = YES;
}
else
{
cell.image.image = [UIImage imageNamed:[listManager.myLists[indexPath.row-1] valueForKey:keyDetailImage]];
cell.label.text = [listManager.myLists[indexPath.row-1] valueForKey:keyName];
cell.imageBadge.hidden = !self.editing;
NSLog(@"selected is %d",cell.selected);
if ( cell.selected )
{
cell.imageBadge.image = self.badgeSelected;
}
else
{
cell.imageBadge.image = self.badgeUnselected;
}
}
return cell;
}
Upvotes: 0
Views: 57
Reputation: 1805
Woah! Checking for a cell
's selected
state from within cellForAtIndexPath:
is guaranteed to not work.
Since you have already created a custom cell subclass SMListCollectionViewCell
, you need to override its selected
setter & toggle the image to be shown on cell from in there.
Since the imageBadge
attribute is already exposed in SMListCollectionViewCell.h
, a quick snippet of only .m
would look like:
// SMListCollectionViewCell.m
#import "SMListCollectionViewCell.h"
@implementation SMListCollectionViewCell
...
- (void)setSelected:(BOOL)selected{
[super setSelected:selected];
if (selected){
cell.imageBadge.image = self.badgeSelected;
}
else {
cell.imageBadge.image = self.badgeUnselected;
}
}
@end
👆🏼 This will handle toggling of images depending on cell selection state.
Additionally, cellForItemAtIndexPath:
will now morph to:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
SMListCollectionViewCell *cell = (SMListCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
if (!indexPath.row){
cell.image.image = [UIImage imageNamed:@"Add"];
cell.label.text = @"Create New";
cell.imageBadge.hidden = YES;
}
else {
cell.image.image = [UIImage imageNamed:[listManager.myLists[indexPath.row-1] valueForKey:keyDetailImage]];
cell.label.text = [listManager.myLists[indexPath.row-1] valueForKey:keyName];
cell.imageBadge.hidden = !self.editing;
}
return cell;
}
Upvotes: 1