remove the subviews from the contentView of UITableViewCell (reset the UITableView)

Viewed 33972

Any idea on how to reset a UITableView?

I want to display a new set of data at the press of a button and also remove all the subviews from the cell's contentView and refresh them with a new set of subviews. I tried [tableView reloadData] but the data did get refreshed but the subviews added to the contentView of the cells previously persisted.

9 Answers

cell.contentView.subviews.forEach({ $0.removeFromSuperview() })

for subview in cell.contentView.subviews {
    subview.removeFromSuperview()
}

you try with replace the content but not the UI, for example to a label replace the text:

class CustomCell : UITableViewCell     {

    var firstColumnLabel = UILabel()

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        firstColumnLabel = //create label

        contentView.addSubview(firstColumnLabel)
    }

    func setData(cad: String) {
        firstColumnLabel.text = cad
    }
}

and in your tableSource

 public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell : UITableViewCell?
        cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCell
            (cell as! CustomCell).setData(cad: "new value")
        return  cell!
    }
Related