Wazza
Wazza

Reputation: 1885

tableview persisting cell image after reloading

I have a tableview with cells that when selected displays an image within the selected cell, this image then disappears when the cell is selected again, and so on. When i press a submit button the selected cells are remembered and the tableview reloads with new data. But when doing this all the new data loads but the selected cell image persists. I have tried calling tableView.reloadData() on the main queue but it still persists. The image also persists when i press the submit button several times.

Heres my code:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return currentQuestion.answers.count
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

    return tableView.frame.height/CGFloat(currentQuestion.answers.count)
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    setSelectedArray()
    let cell: AnswersTableViewCell = tableView.dequeueReusableCell(withIdentifier: "answersTableViewCell") as! AnswersTableViewCell

    let text = currentQuestion.answers[indexPath.row]
    let isAnAnswer = currentQuestion.answerKeys[indexPath.row]

    cell.answerTextLabel.text = text
    cell.answerView.backgroundColor = UIColor.white.withAlphaComponent(0.5)
    cell.contentView.sendSubview(toBack: cell.answerView)

    return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    if let cell: AnswersTableViewCell = tableView.cellForRow(at: indexPath) as? AnswersTableViewCell {

        if cell.answerImageView.image == nil {

            cell.answerImageView.image = UIImage(named: "paw.png")
            selected[indexPath.row] = true

        } else {

            cell.answerImageView.image = nil
            selected[indexPath.row] = false

        }
    }
}

@IBAction func submitButtonWasPressed() {

    if questionNumber < questions.count - 1 {

        questionNumber += 1
        setCurrentQuestion()
        self.answersTableView.reloadData()
        self.view.setNeedsDisplay()
    }
}

Any help would be great. Thanks

Upvotes: 0

Views: 479

Answers (1)

Connor Neville
Connor Neville

Reputation: 7351

You need to set the image back to its correct value in cellForRow. Cells in your table are reused between calls to reloadData, and since you're not touching the imageView, it's keeping its previous value. Looks to me like you want:

cell.answerImageView.image = selected[indexPath.row] ? UIImage(named: "paw.png") : nil

inside of tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath).

Upvotes: 2

Related Questions