当UICollectionView滚动时,UICollectionViewCell中的subView显示错误

时间:2013-07-05 01:49:02

标签: ios uicollectionview uicollectionviewcell

我制作了自定义UICollectionViewCell并在其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;
}

我将 collectionView 作为subView添加到 Viewcontroller ,并正确设置它的框架,现在collectionView显示 coverImageView certifyImageView 通常情况下,但是当我滚动collectionView时, certifyImageView 在错误的单元格上显示,我想这可能是由重用单元格引起的,以及如何单独引起它?

1 个答案:

答案 0 :(得分:2)

我认为因为它重新使用已经将certifyImageView.hidden设置为NO的单元格,所以你必须将它设置回YES 也许试试这个

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

这样你就可以确保certifyImageView被设置为隐藏,如果这就是你想要的。