Antonio K
Antonio K

Reputation: 154

How to get reference to the cell from user function

I create my custom cell with UILabel and Button inside. After I connect the UIButton as action in my Controller. If touch up the Button it changes the image how intended, but what I want is, that after the touch to change the backgoundcolor of the UILabel too. How to get reference to my custom cell.

@IBAction func selectCell(_ sender: UIButton) {
    if sender.imageView?.image == UIImage(named: "do") {
        sender.setImage(UIImage(named: "done"), for: .normal)
    } else {
        sender.setImage(UIImage(named: "do"), for: .normal)
    }
}

Upvotes: 0

Views: 59

Answers (1)

Matthias
Matthias

Reputation: 1026

why not use a delegate system ? This would allow you to get a reference to your cell easily.

In you cell.swift

@objc protocol CellDelegate: class {
    func buttonPressed(forCell cell: Cell)
}

Then in your cell class : you need to have a delegate property, your IBAction method, and a way to set your delegate:

class Cell {

    fileprivate weak var delegate: CellDelegate? = nil


    func setup(withDelegate delegate: CellDelegate) {
        self.delegate = delegate
    }


    @IBAction func deleteButtonPressed(_ sender: Any) {
        if sender.imageView?.image == UIImage(named: "do") {
            sender.setImage(UIImage(named: "done"), for: .normal)
        } else {
            sender.setImage(UIImage(named: "do"), for: .normal)
        }

        delegate?.buttonPressed(forCell: self)
    }

}

Finally in your TableViewController : You need to setup the delegate as self during the configuration of the cell, and implement the delegate method:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellIdentifier = viewModel.cellIdentifier(for: indexPath)

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

            cell.setup(withDelegate: self)

        return cell
    }


extension: TableViewController: CellDelegate {

    func buttonPressed(forCell cell: Cell) {
        //Do what you want
    }

}

That's how I tipically set actions for cells

Upvotes: 1

Related Questions