DCMaxxx
DCMaxxx

Reputation: 2574

Add custom subview to certain reusablecells in UITableView

I have a reusable cell in my UITableview, and I'd like to add a custom image only on certain cells.

Here is my code for example :

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BCContactCell * cell = [tableView dequeueReusableCellWithIdentifier:contactCellIdentifier];
    ...
    if ([contact isFavorite]) {
        UIImageView * fav = [[UIImageView alloc] initWithFrame:CGRectMake(280.0f, 2.0f, 32.0f, 32.0f)];
        [fav setImage:favoriteImg]; // already loaded
        [cell addSubview:fav];
    }
}

It works, and every favorite contact has the picture in its cell. Except when I swipe down, other cell starts to take the picture as well, and I can't seem to figure it out.

Anyone can help me on how to do this ?

Thanks !

Upvotes: 2

Views: 1414

Answers (1)

Thilina Chamath Hewagama
Thilina Chamath Hewagama

Reputation: 9040

Here we go,

give a tag number to your imageview, fav.tag = 1290; later using that number we can get the old uiimageview back and remove it from the cell.
else{ [[cell viewWithTag:1290] removeFromSuperview]; }

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BCContactCell * cell = [tableView dequeueReusableCellWithIdentifier:contactCellIdentifier];
    ...
    if ([contact isFavorite]) {
        UIImageView * fav = [[UIImageView alloc] initWithFrame:CGRectMake(280.0f, 2.0f, 32.0f, 32.0f)];
        fav.tag = 1290;
        [fav setImage:favoriteImg]; // already loaded
        [cell addSubview:fav];
    }else{
        [[cell viewWithTag:1290] removeFromSuperview];
    }
}

When it comes to UITableViewCells, they reuse already created cells. When they reuse old once. You have to remove the UIImageView you added to the cell;

Upvotes: 6

Related Questions