OGeek|极客世界-中国程序员成长平台

标题: ios - 滚动后 UICollectionView 不会保持选中状态 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 12:19
标题: ios - 滚动后 UICollectionView 不会保持选中状态

当我选择一个单元格时,它会变成蓝色,这很好。然后,当我向上滚动并且单元格不在 View 中时,它会变回原始颜色。不确定如何解决这个问题。

- (UICollectionViewCell *)collectionViewUICollectionView *)collectionView cellForItemAtIndexPathNSIndexPath *)indexPath{
    UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier"cellIdentifier" forIndexPath:indexPath];
    cell.backgroundColor=[UIColor lightGrayColor];
    [collectionView selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];
    self.collectionView.allowsMultipleSelection=YES;

    return cell;
}

-(void)collectionViewUICollectionView *)collectionView didSelectItemAtIndexPathNSIndexPath *)indexPath {
    UICollectionViewCell *datasetCell =[collectionView cellForItemAtIndexPath:indexPath];
    datasetCell.backgroundColor = [UIColor blueColor];  
}

-(void)collectionViewUICollectionView *)collectionView didDeselectItemAtIndexPathNSIndexPath *)indexPath {
    UICollectionViewCell *datasetCell =[collectionView cellForItemAtIndexPath:indexPath];  
}



Best Answer-推荐答案


在您的第一种方法中,您实际上是在告诉 Collection View 选择它要求的任何单元格。相反,您应该检查您返回的单元格是否与所选单元格具有相同的路径,然后才给它颜色:

- (UICollectionViewCell *)collectionViewUICollectionView *)collectionView cellForItemAtIndexPathNSIndexPath *)indexPath
{
    UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier"cellIdentifier" forIndexPath:indexPath];
    if ([indexPath isEqual:self.selectedIndexPath]) // you need to create selectedIndexPath as a property
    {
        cell.backgroundColor=[UIColor blueColor];
    }
    else
    {
        cell.backgroundColor=[UIColor lightGrayColor];
    }
    return cell;
}

然后:

-(void)collectionViewUICollectionView *)collectionView didSelectItemAtIndexPathNSIndexPath *)indexPath 
{
    self.selectedIndexPath = indexPath;
}

关于ios - 滚动后 UICollectionView 不会保持选中状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34322802/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4