apploft / APLExpandableCollectionView

UICollectionView subclass with vertically expandable and collapsible sections
MIT License
110 stars 14 forks source link

It seems that indexPath in cellForItemAtIndexPath not working properly - if cells are not visible #7

Closed nor0x closed 9 years ago

nor0x commented 9 years ago

Hello,

I have extended the Demo to display a + or a - label in the section cells. I use cellForItemAtIndexPath to hide the label on item 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 label is hidden on some section cells and some item cells. I don't know why this happens - indexPath.item == 0 should check if a specific cell is a section or an item? It seems that this issue is only present, if cells are not visible. After scrolling down and revealing new cells in the collection view - the label is not visible. ios simulator screen shot 23 jun 2015 16 50 12

michaelkamphausen commented 9 years ago

The cells are reused. When you scroll down, you see section cells that have been item cells before. You need to explicitly set cell.label_OnOff.hidden = NO; in cellForItemAtIndexPath, when indexPath.item == 0. Additionally, you might want to check if a section is expanded or not before setting label_OnOff.text like cell.label_OnOff.text = isExpanded ? @"-" : @"+"; for the same reason.

nor0x commented 9 years ago

Thank you for the answer! -fixed it