当我选择一个单元格时,它会变成蓝色,这很好。然后,当我向上滚动并且单元格不在 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];
}
在您的第一种方法中,您实际上是在告诉 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/
欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) | Powered by Discuz! X3.4 |