How to append and remove selected row cells in tableview cell with a custom button?

protocol MealCellDelegate: AnyObject {
    func didSelect(cell: MealCell)
}

class MealCell: UITableViewCell {
    
    var delegate: MealCellDelegate?

    @IBOutlet weak var checkBtn  : UIButton!

}

I have a UITableViewCell for a select func

And I have a UIViewController like below.

class MealSearchViewController: UIViewController {
    @IBOutlet weak var tableview : UITableView!

    tableview.delegate = self

}
extension MealSearchViewController: MealCellDelegate     {
    func didSelect(cell: MealCell) {
        if let indexPath = tableview.indexPath(for: cell) {
            let selectedItem = meals[indexPath.row]
            selectedMeals.append(selectedItem)
            
        }
    }
}

But This code dose not work. I want to append to an empty array when I clicked a checking button (It's status is selected) and I remove from the array when I deselect that button. Help me plz


Solution 1:

Cell code:

protocol MealCellDelegate: AnyObject {
    func didSelect(cell: MealCell)
}

class MealCell: UITableViewCell {
    
    var delegate: MealCellDelegate?

    @IBOutlet weak var checkBtn: UIButton!

    @IBAction func buttonClicked() {
        delegate?.didSelect(cell: self)
    }
}

UIViewController code:

class MealSearchViewController: UIViewController {
    @IBOutlet weak var tableView : UITableView!
    
    override func viewDidLoad() {
        tableView.dataSource = self
    }
}

extension MealSearchViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        cell = *create meal cell*
        cell.delegate = self
        return cell
    }
}

extension MealSearchViewController: MealCellDelegate     {
    func didSelect(cell: MealCell) {
       *it calls after you press button in cell* 
    }
}