Search code examples
xcodeuitableviewcustom-cell

Custom UITableViewCells Reloading Issue


Whenever I delete a cell the cell that was previously in its place imageViews don't disappear. For example a cell uses all three image views, and was deleted and replaced by a cell that one used one of the image views. The two images views with the images of the previous cell (Which was deleted) remain. When I delete a cell I remove the object from an nsmutablearray and do reloadData on the uitableview.

I made a custom uitableviewcell which looks like

@interface MyPetTableViewCell : UITableViewCell

@property (nonatomic, weak) IBOutlet PetNameLabel *petName;
@property (nonatomic, weak) IBOutlet UIImageView *imageOne;
@property (nonatomic, weak) IBOutlet UIImageView *imageTwo;
@property (nonatomic, weak) IBOutlet UIImageView *imageThree;

@end

My UITableView is setup like this

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"PetCell";
    MyPetTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    PetResponse *petItem = self.petListResponse.PetList[indexPath.row];
    NSString *petNameItem = petItem.PetName;
    NSLog(@"PET NAME : %@",petNameItem);
    NSLog(@"NUMBER OF IMAGES : %lu", (unsigned long)petItem.EncodedImages.count);
    for (int i = 0; i < [petItem.EncodedImages count]; i++) {

        NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:petItem.EncodedImages[i] options:0];
        UIImage *image = [UIImage imageWithData:decodedData];
        if (i == 0) {
            cell.imageOne.image = image;
        } else if (i == 1)
        {
            cell.imageTwo.image = image;
        } else if (i == 2)
        {
            cell.imageThree.image = image;
        }
    }
    cell.petName.text = [NSString stringWithFormat:@"%@ :",petNameItem];
    UIColor *customcolor = [UIColor colorWithRed:11/255.0f green:64/255.0f blue:64/255.0f alpha:0.5f];
    cell.petName.backgroundColor = customcolor;
    cell.petName.layer.cornerRadius = 5;
    cell.petName.numberOfLines = 0;
    [cell.petName sizeToFit];

    [cell setBackgroundColor:[UIColor clearColor]];

    NSLog(@"Returning Cell");
    return cell;
}

Solution

  • It is hard to guess what happens, but one possibility is the following:
    Table view cells are re-used. So when you add, e.g., a subview to a table view cell, and the corresponding row of the table view is scrolled out of the screen, the cell (with the subviews!) is put back into the re-use pool. If a new table row should be shown, chances are that the now unused cell (with the old subviews) is taken from the re-use pool, and the old subviews will be shown.
    What could you do in this case is to "prepare a table view cell for re-use", using the method

    - (void)prepareForReuse
    

    In this method, you could remove all old subviews, see the docs.