wayneh
wayneh

Reputation: 4413

Remove subview from UITableView cell

I have a table, and based on a simple boolean, I add a subview containing an image to the right side of the cell using this code in cellForRowAtIndexPath:

if(myArray[indexPath.row]==YES){
    int xpos=self.mainTableView.frame.size.width+self.mainTableView.frame.origin.x-24;
    int ypos=(cell.frame.size.height/2)-(18/2);
    UIImageView *imv=[[UIImageView alloc]initWithFrame:CGRectMake(xpos,ypos, 18, 18)];
    imv.image=[UIImage imageNamed:@"transition-30"];
    [cell.contentView addSubview:imv];
}

If when the value of "myArray[x]" is NO, how can I remove the previously added subview?

I've tried using: [cell.contentView removeFromSuperview] but that removes the entire contents of the cell - text included.

Upvotes: 0

Views: 2233

Answers (1)

DAXaholic
DAXaholic

Reputation: 35348

You have to call removeFromSuperview on imv --> [imv removeFromSuperview];

To get the previously added imv, you could set the tag property of your imv to a constant and get it at the next call with viewWithTag (see here)

So before adding the subview:

imv.tag = 1;
[cell.contentView addSubview:imv];

When deleting the subview you first have to trigger a reload of the desired cell with

reloadRowsAtIndexPaths:(NSArray *)indexPaths 
      withRowAnimation:(UITableViewRowAnimation)animation;  

and then in cellForRowAtIndexPath you do the following if myArray[indexPath.row] == NO

UIImageView *imv = (UIImageView*)[cell.contentView viewWithTag:1];
[imv removeFromSuperview];

Using the tag property is bad practice so consider creating your own UITableViewCell
See here for a description how to do that.

Upvotes: 2

Related Questions