Update not visible cells in UICollectionView

1.9k views Asked by At

I need an expandable UICollectionView in my app - so I came across this project (https://github.com/apploft/APLExpandableCollectionView). It's a subclass of UICollectionView that implements the expand and collapse behaviour.

I have extended the demo app to display a + or a - button in the expandable cells.

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
APLCollectionViewCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"APLCollectionViewCell" forIndexPath:indexPath];

if (indexPath.item == 0) {
    cell.label.text = [NSString stringWithFormat:@"Section %li", (long)indexPath.section + 1];
    cell.backgroundColor = [UIColor colorWithRed:58./255. green:165./255. blue:192./255. alpha:1.];
    cell.indentView.hidden = YES;
    cell.label_OnOff.text = @"+";
} else {
    cell.label.text = [NSString stringWithFormat:@"Item %li", (long)indexPath.row];
    cell.backgroundColor = [UIColor colorWithRed:58./255. green:165./255. blue:192./255. alpha:.5];
    cell.indentView.hidden = NO;
    [cell.label_OnOff setHidden:YES];
}

return cell; 
}

To switch between + and - I implemented the delegate methods:

- (void)collectionView:(UICollectionView *)collectionView didCollapseItemAtIndexPath:(NSIndexPath *)indexPath
{
    APLCollectionViewCell *cell = (APLCollectionViewCell*)[collectionView cellForItemAtIndexPath:indexPath];
    cell.label_OnOff.text = @"+";
}

- (void)collectionView:(UICollectionView *)collectionView didExpandItemAtIndexPath:(NSIndexPath *)indexPath
{
    APLCollectionViewCell *cell = (APLCollectionViewCell*)[collectionView cellForItemAtIndexPath:indexPath];
    cell.label_OnOff.text = @"-";
}

As you can see in the screenshot, the visible cells are updated correctly. Once I scroll down to the former invisible cells, the + button disappears. This problem doesn't occur when there are only a few items in the UICollectionView, so that there is no need to scroll to further items.

Screenshot

Am I doing something wrong with IndexPath for invisble cells, or do you have any other hints for me? Thank you!

2

There are 2 answers

1
nor0x On BEST ANSWER

Thx Bhanu,

your answer pointed me to the right direction. The cells in the collectionview are REUSED, so I had to set cell.label_OnOff.hidden = NO; and cell.label_OnOff.hidden = YES; when I check for the IndexPath.

0
Bhanupriya On

Add the below line

cell.indentView.hidden = NO;

Just before your if else condition in cellForItemAtIndexPath. it may help you.