我正在尝试在UICollectionView
中选择一个单元格,它会被选中,但在向下滚动时会选择底部的其他单元格并向上滚动显示其他要选择的单元格。
以下是我使用的代码didSelectItemAtIndexPath
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
NSIndexPath *newIndex = indexPath;
cell = (CustomCollectionCell *)[collectionView cellForItemAtIndexPath:newIndex];
NSString *strId = [[masterArray valueForKey:@"id"]objectAtIndex:indexPath.row];
NSString *tempIndexRow = [NSString stringWithFormat:@"%ld",(long)indexPath.row];
NSLog(@"%@, %@,%d ,%@, %d", strId,tempIndexRow,cell.imageView.tag,[boolArray objectAtIndex:indexPath.row],indexPath.row);
if (strId && [[boolArray objectAtIndex:indexPath.row] isEqualToString:@"False"] && cell.imageView.tag == indexPath.row) {
cell.selectedImage.image = [UIImage imageNamed:@"select.png"];
[boolArray replaceObjectAtIndex:indexPath.row withObject:@"True"];
}
else{
cell.selectedImage.image = Nil;
[boolArray replaceObjectAtIndex:indexPath.row withObject:@"False"];
}
}
这是我第一次选择
这是我向下滚动时的结果
谢谢
答案 0 :(得分:7)
您需要将所选项索引存储设置为一个数组,并在cellForRowIndex
时使用 indexPath.row 检查此数组索引,如下所示: -
selectedCellsArray
以ViewDIdLoad
方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
cell = (CustomCollectionCell *)[collectionView cellForItemAtIndexPath:newIndex];
if ( [selectedCellsArray containsObject:[NSString stringWithFormat:@"%d",indexPath.row]] )
{
[selectedCellsArray removeObject:[NSString stringWithFormat:@"%d",indexPath.row]];
cell.selectedImage.image = Nil;
}
else
{
[selectedCellsArray addObject:[NSString stringWithFormat:@"%d",indexPath.row]];
cell.selectedImage.image = [UIImage imageNamed:@"select.png"];
}
}
和
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
NSNumber *rowNsNum = [NSNumber numberWithUnsignedInt:indexPath.row];
if ( [selectedCellsArray containsObject:[NSString stringWithFormat:@"%@",rowNsNum]] )
{
cell.selectedImage.image = [UIImage imageNamed:@"select.png"];
}
else
{
cell.selectedImage.image = Nil;
}
}
答案 1 :(得分:0)
没有选择其他单元格。问题最可能是由于您重新使用单元格而不是在它们返回到屏幕时正确地重新定位它们。当单元格不可见时,它会被卸载以节省内存。
因此,在cellForItemAtIndexPath
数据源
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
//You cell initialization code.
if ([[boolArray objectAtIndex:indexPath.row] isEqualToString:@"True"] ) {
cell.selectedImage.image = [UIImage imageNamed:@"select.png"];
}
else{
cell.selectedImage.image = Nil;
}
}