Black Magic
Black Magic

Reputation: 2766

collectionView re-usable cells causing bugs

I am creating a collectionView whose cells are of different sizes and have different content. I am using a cell prototype for these cells, however, when I am adding more than one cell I get weird UI bugs:

This is what it is supposed to look like Supposed to This is what it actually looks like Fail

Code:

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    Card *card = [[[usermanager getSelectedUser] getCards] objectAtIndex:indexPath.item];

    [card setupLayout];

    UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
    if(cell == nil){
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cardCell" forIndexPath:indexPath];
    }
    [cell addSubview:card];
    cell.clipsToBounds = YES;
    cell.layer.shouldRasterize = YES;
    cell.layer.rasterizationScale = [UIScreen mainScreen].scale;

    cell.layer.shadowPath = [[UIBezierPath bezierPathWithRect:cell.bounds] CGPath];

    //Add dropshadow
    cell.contentView.layer.borderWidth = 1.0f;
    cell.contentView.layer.borderColor = [UIColor clearColor].CGColor;
    cell.contentView.layer.masksToBounds = YES;

    cell.layer.shadowColor = [UIColor blackColor].CGColor;
    cell.layer.shadowOffset = CGSizeMake(0, 5.0f);
    cell.layer.shadowRadius = 2.0f;
    cell.layer.shadowOpacity = 0.5f;
    cell.layer.masksToBounds = NO;

    cell.layer.borderColor = [UIColor yellowColor].CGColor;
    cell.layer.borderWidth = 2.0f;

    return cell;
}

It propably has something to do with the fact that I use the reusable cell. Because when I create 2 different prototypes in my storyboard for these cells they have no problems at all. Can anyone help me? Thanks

Upvotes: 1

Views: 684

Answers (1)

thorb65
thorb65

Reputation: 2716

as you say: your cells will be reused, so if you change any layout or frame or colour these properties will be like you set when the cell will be used the next time. you should subclass UICollectionViewCell and implement the method prepareForReuse where you have to reset all views and properties of the cell to the original values and you have to remove the subview card:

-(void)prepareForReuse {
    [super prepareForReuse];
    // Reset all, for example backgroundView
    self.backgroundView = nil;
}

one more point: why you call UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath]; Thats not correct. You need only UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cardCell" forIndexPath:indexPath];

Upvotes: 4

Related Questions