【发布时间】:2017-07-08 14:10:31
【问题描述】:
我已经制作了一个图像网格,为了显示它的选择,我在选择时为图像绘制了边框。但问题是当我在顶部选择一些图像并向下滚动图像网格时,底部的一些其他图像似乎也被选中了。下面是我的代码sn-p:
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;
}
我可以猜到重用单元格出了点问题,但不确定也想不出解决问题的想法。 等待任何形式的帮助和建议。
提前致谢。
【问题讨论】:
-
尝试使用 indexPath.item 代替 indexPath.row。如果您仍然遇到任何问题,请告诉我
-
感谢您的建议 Anurag,但 indexpath.item 的工作方式仍然与 indexpath.row 相同......
标签: ios uicollectionview