John
John

Reputation: 1015

TableView Cells changing on reload and not displaying correct content | Swift

I have a tableview that loads custom cells from a JSON array. I noticed on the first load the cells look perfectly fine. On the second load (pull to refresh) the cells are no longer following the design logic expressed in cellForRowAt - instead random cells will start displaying the color meant for other cells and images meant to be hidden.

An example of the logic failing on reload is the UIImage named "fGlyph" is being displayed where item.type == "locate" then after a refresh the tableview will display the UIImage on a completely incorrect cell.

Upvotes: 0

Views: 740

Answers (2)

Noman Umar
Noman Umar

Reputation: 409

in tableView Cell use below code

override func prepareForReuse() {
    self.cellImage.image = UIImage(named: "")
}

or use cell.cellImage.image = UIImage(named: "") in else block

   //Setting Images
    if item.type == "locate" {
        cell.stopnumLabel.text = ""
        cell.cellImage.image = UIImage(named: "fGlyph")
    } else {
        cell.cellImage.image = UIImage(named: "")
        cell.stopnumLabel.text = "\(item.stoporder)"
    }

Upvotes: 4

Shreeram Bhat
Shreeram Bhat

Reputation: 3157

In tableview, cells are reused instead of recreated. So you need to reset cell parameters before reuse. Otherwise old data will show up in unexpected places. Below is the function to do that

override func prepareForReuse() {
    self.cellImage.image = UIImage(named: "")
}

Upvotes: 1

Related Questions