首页 文章

在UITollectionViewCell中UIImageView在UITableViewCell中的bug

提问于
浏览
2

UICollectionView 的设置是使用IB定义的(即滚动方向:水平等),并使用IB嵌入 UITableViewCell .

UICollectionViewCell 显示,图像显示但是,图像堆叠在一起,而不是每一个图像 cell 具有保真度 .

images stacked on top of one another

我为每个图片制作了单独的 UIImageView 作为实例变量,并且使用 cellForItemAtIndexPath 消息中的if和 switch 语句进行了相同的操作 .

由于使用了IB,因此识别错误可能是一个延伸,但是,如果从代码中显而易见,请帮助识别错误?谢谢 .

@implementation AccountTableViewCell

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state

    imageArray = @[[UIImage imageNamed:@"image1.png"], [UIImage imageNamed:@"image2.png"], [UIImage imageNamed:@"image3.png"], [UIImage imageNamed:@"image4.png"], [UIImage imageNamed:@"image5.png"]];

    self.oCollectionView.dataSource = self;
    [self.oCollectionView setFrame:self.contentView.frame];
    [self.contentView addSubview:self.oCollectionView];
    self.oCollectionView.backgroundColor = [UIColor clearColor];
    [self.oCollectionView reloadData];
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return imageArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"accountCell" forIndexPath:indexPath];

    UIImageView* iv = [[UIImageView alloc] init];
    [cell.contentView addSubview:iv];
    [iv setFrame:cell.contentView.frame];
    iv.image = imageArray[indexPath.row];

    return cell;
}

@end

1 回答

  • 1

    这是因为你每次出列时都会继续向 cell 添加 UIImageView .

    相反,你应该继承 UICollectionViewCell (让我们称之为"MYCollectionViewCell",将 UIImageView 添加到 storyboardcell 子类中,并将 UIImageView 设置为子类的出口 .

    然后,在 cellForItemAtIndexPath 内,设置 imageView's 图像如下:

    - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
    {
        MyCollectionViewCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"accountCell" forIndexPath:indexPath];
    
        cell.imageView.image = imageArray[indexPath.row];
    
        return cell;
    }
    

相关问题