4

I have an UICollectionViewController and my custom cells, and in my cellForRowAtIndexPath: method I set the cells based on indexPath.row. But I am getting wrong results, this cell appears even after first position, and if you scroll back and forth, it pops up in random places. How do i fix that?

Here is the code:

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    DVGCollectionViewCell *cell;

    cell = [self.collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];

    if (indexPath.row == 0)
    {
        cell.imageView.image = [UIImage imageNamed:@"something1.png"];
        cell.buyLabel.text = @"170";
        cell.textLabel.text = @"11.2011";
    }

    return cell;
}
Dvole
  • 5,483
  • 8
  • 50
  • 86

4 Answers4

4

Cell in both UITableView and UICollectionView are recycled, that means that when one goes off screen it is put in an NSSet until you need it again. When it's need it's removed from the set ad added again at UICollectionView views hierarchy. If you do not clean the value inside the cell or set them again, the cell will show the same data when it was created.
This is made for performance reason creating cell takes more time instead of value them again.
If your problem is in layout check the layout flow object, which size did you set?

Andrea
  • 24,774
  • 10
  • 79
  • 121
1

I have found the problem, once the cell contents was set it was never cleaned. So I added cleaning every cell properties as additional clause and it works fine.

Dvole
  • 5,483
  • 8
  • 50
  • 86
1

You can perform any clean up necessary to prepare the view for use again if you override prepareForReuse in your custom cell implementation.

Attila H
  • 3,506
  • 1
  • 22
  • 36
0

One of the answers in this SO post helped: override prepareForReuse and reset the cell to its default state. Don't forget to call super.prepareForReuse.

Community
  • 1
  • 1
Crashalot
  • 31,452
  • 56
  • 235
  • 393