我制作了一个图像网格,为了显示它的选择,我在选择时为图像绘制了边框。但问题是当我在顶部选择一些图像并向下滚动图像网格时,底部的一些其他图像似乎也被选中了。下面是我的代码片段:
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];
以上已添加到 viewDidLoad 中,并在 nib 中设计了集合视图单元。
并实施了以下代表:
-(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;
}
我可以猜测重复使用该单元时出了点问题,但不确定并且无法解决它。等待任何形式的帮助和建议。
提前致谢。