集合视图在滚动时更改选定的单元格

 誓言俱乐部 发布于 2023-02-09 15:34

我正在尝试选择一个单元格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"];
    }
}

这是我第一次选择的

在此输入图像描述

这是我向下滚动时得到的结果

在此输入图像描述

谢谢

1 个回答
  • 您需要将所选项目索引存储设置为一个数组,并 cellForRowIndex使用indexPath.row检查此数组索引,如下所示: -

    selectedCellsArrayViewDIdLoad方法中分配此数组

    - (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;
            }
    }
    

    2023-02-09 15:37 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有