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
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!
}
For Swift 3.1
let theSubviews: Array = (cell?.contentView.subviews)!
for view in theSubviews
{
view.removeFromSuperview()
}
cell.contentView.subviews.forEach({ $0.removeFromSuperview() })
Instead of iterating through all the subviews (yourself) to remove them, you can simply do this,
[[scrollView subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];
I know this question is old, but i found a problem with the solution, if you remove one subview from one prototype cell, this view will be removed from all reused cells, this will create a null pointer in the next cell that will be reused.
If you subclass UITableViewCell and remove the subview from there, you will have to do this verification first:
if (mySubView != nil ) {
mySubView.removeFromSuperview()
}
This also will work inside your cellForRow at indexPath method
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! MyCustomCell
if (cell.mySubView != nil) {
cell.mySubView.removeFromSuperview()
}
return cell
}
Whit this you avoid the null pointer, the code is for swift 3. Hope this help somebody. :)
If you want to remove all the subviews of a UITableViewCell you can use this code:
NSArray* subviews = [cell.contentView subviews];
for (UIView* subview in subviews) {
[subview removeFromSuperview];
}
Using the code of @leftspin