Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

subView in UICollectionViewCell displayed wrong when UICollectionView scrolled

I make a custom UICollectionViewCell and add a subView to its contentView:

BooksCell.h

@interface BooksCell : UICollectionViewCell
@property (strong, nonatomic) UIImageView *certifyImageView;
@end

BooksCell.m

- (id)initWithFrame:(CGRect)frame {
    self= [super initWithFrame:frame];
    if(self){
        _coverImageView = [[UIImageView alloc] initWithFrame:CGRectMake(15, 15, 88, 117)];
        _coverImageView.userInteractionEnabled = YES;
        [self.contentView addSubview:_coverImageView];

        UIImage *certifyImage = [UIImage imageNamed:@"13-6.png"];
        _certifyImageView = [[UIImageView alloc] initWithFrame:CGRectMake(17.5, _coverImageView.frame.size.height-3, certifyImage.size.width, certifyImage.size.height)];
        _certifyImageView.image = certifyImage;
        _certifyImageView.hidden = YES;
    }
    return self;
}

ViewController

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    BooksCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"BooksCell" forIndexPath:indexPath];
    cell.coverImageView.image = [UIImage imageNamed:@"13-5.png"];

   // **Here I want some cell display certifyImageView and some not.**
    if(indexPath.row%2==0){
        cell.certifyImageView.hidden = NO;
    }

    return cell;
}

I add the collectionView as subView to the Viewcontroller, and set it's frame correctly, now the collectionView displaied coverImageView and certifyImageView normally, but when I scroll the collectionView, certifyImageView displaied on the wrong cell,I guess it maybe caused by the Reuse Cell, and how to sole it?

like image 457
Mil0R3 Avatar asked Feb 15 '26 07:02

Mil0R3


1 Answers

I think because it is reusing the cell that already set the certifyImageView.hidden to NO so you have to set it back to YES Maybe try this

if(indexPath.row%2==0){
        cell.certifyImageView.hidden = NO;
    }
else{
       cell.certifyImageView.hidden = YES;
}

This way you will make sure that the certifyImageView will be set to hidden if thats what you want.

like image 111
Yan Avatar answered Feb 16 '26 22:02

Yan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!