Reputation: 47
When I select a cell, it turns blue, which is good. Then when I scroll up and the cell out of view, it turns back to original color. Not sure how to fix this.
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)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)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *datasetCell =[collectionView cellForItemAtIndexPath:indexPath];
datasetCell.backgroundColor = [UIColor blueColor];
}
-(void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *datasetCell =[collectionView cellForItemAtIndexPath:indexPath];
}
Upvotes: 3
Views: 1442
Reputation: 1288
In your first method, you are practically telling the collection view to select any cell that it asks for. Instead, you should check whether the cell you return has the same path as the selected one, and only then give it color:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)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;
}
And then:
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
self.selectedIndexPath = indexPath;
}
Upvotes: 3
Reputation: 3429
When cell are reused, the selection state is lost. So you need to save the indexPath of the selection in didSelectItemAtIndexPath. And when you dequeue the cell you need to check and restore the state
Upvotes: 2