i have made a grid of images and in order to show its selection i drew border for the image when selected. but the problem is when i select some image at the top and scroll down the grid of images, some other image at the bottom also seemed to be selected. below is my code snippet:
UINib *cellNib = [UINib nibWithNibName:@"collectionCell" bundle:nil];
[self.collectionView registerNib:cellNib forCellWithReuseIdentifier:@"cellCV"];
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
[flowLayout setItemSize:CGSizeMake(95, 95)];
[flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
[self.collectionView setCollectionViewLayout:flowLayout];
Above has been added in viewDidLoad with the collection view cell designed in nib.
and implemented following delegates:
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
selectedImageIndex = indexPath.row;
[collectionView reloadData];
}
-(CollectionCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UIImage *img = [imageArray objectAtIndex:indexPath.row];
static NSString *cellIdentifier = @"cellCV";
CollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:
cellIdentifier forIndexPath:indexPath];
cell.imageView.image = img;
cell.imageView.tag = indexPath.row;
UIImageView *imgView = (UIImageView *)[cell viewWithTag:indexPath.row];
if (indexPath.row == selectedImageIndex) {
imgView.layer.borderWidth = 4.0;
imgView.layer.borderColor = [UIColor redColor].CGColor;
NSLog(@"selected indexpath: %d", indexPath.row);
}
else {
imgView.layer.borderWidth = 0.0;
imgView.layer.borderColor = nil;
}
return cell;
}
i could guess that something is going wrong with reusing the cell, but not sure and couldnt het an idea to resolve it. Waiting for any kind of help and suggestions.
Thanks in advance.
I'm not seeing why this would take place. I do not believe the issue is the use of
row
vsitem
, though you really should useitem
. I can imagine, though, if your collection view has more than onesection
, that only looking atrow
/item
but ignoringsection
would be a problem (i.e. it would select the sameitem
number in everysection
).To cut the Gordian knot, I'd suggest saving the
NSIndexPath
of the selected item, and then using that for the basis of comparison. That also makes it easy to render an optimization indidSelectItemAtIndexPath
. Anyway, first define your property:And then implement
cellForItemAtIndexPath
anddidSelectItemAtIndexPath
:As an aside, note that I'm not messing around with the
tag
property (I see no value in that). Also note that rather than reloading entire collection view, I'm only reloading the selected cell (and if there was a previous selected cell, that one too), which should be more efficient.This code is in Swift 3: