1110
1110

Reputation: 6839

Duplicating images on scroll - is there fix without subclassing?

I have a UITableView and some items have image on the left side.

When I scroll up-down a few times image getting copied all the time to the rows that doesn't have image. How to fix this?

Here is my code:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    Object* obj = [_list objectAtIndex:indexPath.row];

    if(cell == nil){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
    }

    cell.textLabel.text = obj.Title;

    if(obj.Image != nil){
    cell.imageView.image = obj.Image;
    }

    return cell;
}

Upvotes: 0

Views: 33

Answers (2)

Merlevede
Merlevede

Reputation: 8180

You need to consider the case when obj.Image is nil explicitly. Because the cell is being reused it will also reuse its image if you don't change it.

if(obj.Image != nil){
    cell.imageView.image = obj.Image;
}
else
{
    cell.imageView.image = nil;
}

Upvotes: 1

Putz1103
Putz1103

Reputation: 6211

How about just adding an else statement:

if(obj.Image != nil)
{
    cell.imageView.image = obj.Image;
}
else
{
    cell.imageView.image = nil;
}

Upvotes: 1

Related Questions