取消选择单元格时,集合视图中的didDeselectItemAtIndexPath不会触发

时间:2014-10-07 15:32:02

标签: ios

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
        UIImageView *img;
        UICollectionViewCell *myCell=[collectionView cellForItemAtIndexPath:indexPath];
        img=(UIImageView*)[myCell viewWithTag:101];
        if (myCell.selected) {
            [myCell.img setImage:[UIImage imageNamed:@"images-2.png"]];
        }

        [collectionView reloadData];
    }

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath{
        UIImageView *img;
        UICollectionViewCell *myCell=[collectionView cellForItemAtIndexPath:indexPath];
        img=(UIImageView*)[myCell viewWithTag:101];
        [img setImage:[UIImage imageNamed:@"images.png"]];
       [collectionView reloadData];
    }

2 个答案:

答案 0 :(得分:0)

不要在委托回调中调用reloadData。这很容易导致未定义的行为,并且还会导致您提到的有关集合视图无法正确处理选择状态的问题。

通常调用reloadData会删除所有选择。

答案 1 :(得分:0)

[collectionView reloadData];的问题 重新加载数据后,您将更改cellForItemAtIndexPath

中的图像
  -(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
    {
     UICollectionViewCell *cell = (UICollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    if(indexPath.row == selectedIndexPath)
    {
    [img setImage:[UIImage imageNamed:@"selected image"]];
    }
    else
    {
    [img setImage:[UIImage imageNamed:@"images.png"]];
    }
}

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
     selectedIndexPath=indexPath.row;
     [collectionView reloadData];
}

注意:最初设置selectedIndexPath = -1,表示在集合视图中没有选择