iDev_91
iDev_91

Reputation: 317

UICollectionView images

I have an UICollectionView with images, now I want to add a sticker to all images from 5th image to the end. I use the following code, and It works, but when I scroll down to the end, then scroll it back, all stickers appears on ALL IMAGES.

 - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"Cell";

    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];

    UIImageView *recipeImageView = (UIImageView *)[cell viewWithTag:100];
    recipeImageView.layer.borderWidth = 0.3;
    recipeImageView.layer.borderColor = [UIColor blackColor].CGColor;
    recipeImageView.image = [UIImage imageNamed:[wallPack objectAtIndex:indexPath.row]];

    // add Paid stickers
    NSString *stickName = [NSString stringWithFormat:@"stickerImage.png"]; /// image name
    UIImage *stickImage = [UIImage imageNamed:stickName];

    stickView = [[UIImageView alloc] initWithImage:stickImage];
    stickView.contentMode = UIViewContentModeScaleAspectFit;

    if (indexPath.row >= 5) {

        [recipeImageView addSubview:stickView];

    }


    return cell;
}

where is the problem? why before scrolling down everything appears as I want, from 5th to the end, but when I scroll it back, the sticker image puts on ALL images.

Upvotes: 0

Views: 149

Answers (2)

RandomGuy
RandomGuy

Reputation: 127

I would suggest creating UICollectionViewCell subclass wherein you can add a property for stickImage and set it (based on your condition). Moreover in prepareForReuse function you can default it to whatever you want, it will also make your - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath a bit more cleaner.

Upvotes: 0

matt
matt

Reputation: 534893

The cells are reused. You must add the sticker to the ones you want to add it to if it is not there, but also remove it from the ones where you don't want want it if it is there.

Upvotes: 1

Related Questions