Search code examples
swiftuitableviewbuttoncell

Change Image Button in cell of table view


I have two classes TableViewController and CustomCell then connect the button(likeBtn) in IB to CustomCell.

And now, I wanna to change the image of this button!

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellIdentifier = "Cell"

        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! CustomCell

        // Configure the cell...            
        cell.likeBtn.addTarget(self, action: #selector(TableViewController.liked), for: .touchUpInside)

        return cell
    }

@objc func liked(sender: UIButton) {

        cell.likeBtn.setImage(UIImage(named: "liked.png"), for: .normal)
        cell.likeBtn.isUserInteractionEnabled = false
    }

But in the liked(), I've errors about cell.likeBtn.

I'm programming with swift 4


Solution

  • The correct way should be:

    @objc func liked(sender: UIButton) {
        sender.setImage(UIImage(named: "liked.png"), for: .normal)
        sender.isUserInteractionEnabled = false
    }