3

我做了一个自定义UICollectionViewCell并将一个 subView 添加到它的 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;
}

视图控制器

- (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 正常显示了coverImageViewcertifyImageView,但是当我滚动 collectionView 时,certifyImageView显示在错误的单元格上,我猜这可能是由Reuse Cell引起的,并且如何鞋底?

4

1 回答 1

2

我认为因为它正在重用已将 certifyImageView.hidden 设置为 NO 的单元格,所以您必须将其设置回 YES 也许试试这个

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

这样,您将确保 certifyImageView 将设置为隐藏,如果那是您想要的。

于 2013-07-05T02:25:47.123 回答