0

I'm trying to implement a quite simple TableView, in which I got a Prototype Cell containing a Heart-Shaped Button. When I click on that Button, I want to change that Buttons color (precisely: the Image of the Button) to be filled.

It actually works, but not only the selected Cell fills its Heart Button, but every 4th Cell does so and I have no clue why and how to change that.

Here's the cellForRowAt method, where I access the Cells' Heart Button and define the target for when its clicked:

func tableView(_ tableView: UITableView, cellForRowAt indexPath:  IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! CustomCell

    [...]

    if let likeButton = cell.likeButton {
        likeButton.tag = indexPath.row
        likeButton.addTarget(self, action: #selector(likeButtonClicked(sender:)), for: .touchUpInside)
    }
    cell.initUI()

    return cell
}

... and here's the target method "likeButtonClicked":

@objc func likeButtonClicked(sender: UIButton) {

    sender.isSelected = !sender.isSelected

    if sender.isSelected {
        sender.setImage(UIImage(named: "like-icon-filled.png"), for: .normal)

    } else {
        sender.setImage(UIImage(named: "like-icon-empty.png"), for: .normal)

    }

}

Thinking logically, there must be multiple senders at once, that are changed in this method, but I don't know, please help me out.

1 Answers1

1

You are dequeuing (reusing) cells, so you should reset the image of the likeButton:

func tableView(_ tableView: UITableView, cellForRowAt indexPath:  IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! CustomCell

    [...]

    if let likeButton = cell.likeButton {
        likeButton.tag = indexPath.row
        likeButton.setImage(UIImage(named: "like-icon-empty.png"), for: .normal)
        likeButton.addTarget(self, action: #selector(likeButtonClicked(sender:)), for: .touchUpInside)
    }
    cell.initUI()

    return cell
}
ielyamani
  • 17,807
  • 10
  • 55
  • 90
  • Thanks for the quick answer, I tried and it seems to work, but as soon as I scroll down (so the selected Cell is out of view) and back up again, the likeButton ist resetted just like I never clicked it... any Ideas? – Tightus Sep 13 '18 at 14:56
  • @TitusTissot in setting the image to be empty or not, must depend on your data source. For example, you could have an array of rows that are *liked*. And based on that you set the image. – ielyamani Sep 13 '18 at 14:59