Back to erase subviews of a TableView after a reload?

0

I have a TableView to which in each cell I add several imageView. In a moment of the application I have to change the imgeView of a cell in one position for another imageView therefore I do a reload of the tableView. The problem is that when doing the reload, it adds the new one over the previous imageView of the cell. What I want is that before doing the reload this cell is deleted all the subviews, but I can not find the method to do it.

When I add the imageView I do it as 'imageView.tag = indexPath.row;' and 'cell addSubview: imageView'

To erase the above, at the start of the load code of the tableView I do it as: '[[cell viewWithTag: indexPath.row] removeFromSuperview];' so when I do the reload I also erase it but it does not work for me.

    
asked by Popularfan 17.03.2017 в 16:42
source

1 answer

2

I would tell you that you will use 2 different cell types for each purpose. So you would not have to completely modify the UI of the cell in question at runtime, and you could take advantage of the cells to be reused, saving resources and being more efficient.

However, if you still want to be able to delete all the elements of a cell, you could do the following, in the class you inherit from UITableViewCell that you use for the cell in question, overwrite the prepareForReuse method, which is called every time a cell is going to be reused.

override func prepareForReuse() {
    super.prepareForReuse()
    contentView.subviews.forEach({ $0.removeFromSuperview() })
}

If you only want to eliminate those that are imageView you can modify the line by the following:

contentView.subviews.filter({ $0 is UIImageView }).forEach({ $0.removeFromSuperview() })

EDIT: Seeing that you need to do it in Objective-C would be like this:

- (void)prepareForReuse {
    [super prepareForReuse];

    for (UIView *subview in self.contentView.subviews) {
        if ([subview isKindOfClass:[UIImageView class]]) {
            [subview removeFromSuperview];
        }
    }
}
    
answered by 03.04.2017 / 10:45
source