简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM