2
votes

The settings for the UICollectionView were defined using IB (ie scroll direction: horizontal, etc), and was embedded in UITableViewCell using IB.

UICollectionViewCell displays, images display, however, images are stacked on top of one another, instead of one image per one cell with fidelity.

images stacked on top of one another

I made individual UIImageView for each picture as instance variables, and same occurred using if and switch statements in the cellForItemAtIndexPath message.

Since IB was used, it may be a stretch to identify the bug, however, would you please help to identify the bug in case it is obvious from the code? Thanks.

@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 Answers

1
votes

It's because you keep on adding an UIImageView to the cell each time it's dequeued.

Instead, you should subclass the UICollectionViewCell (let's call it "MYCollectionViewCell", add a UIImageView to the cell subclass in the storyboard and set the UIImageView as an outlet on the subclass.

Then, within cellForItemAtIndexPath, set that imageView's image like so:

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

    cell.imageView.image = imageArray[indexPath.row];

    return cell;
}