I'm learning combine and I want to use combine instead a delegate between cell and tableview. I have managed to connect and receive the information, but the problem is when the cell is reused, every time I generate the same event, I receive it as many times as it has been used previously in that reused cell.
I have declared cancelables in the view controller as
var cancellables: Set<AnyCancellable> = []
And this is the cellForRow method
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: MyCell.celdaReuseIdentifier, for: indexPath)
as? MyCell else {
return MyCell()
}
cell.index = indexPath
cell.lbTitle.text = String("Cell \(indexPath.row)")
cell.tapButton.compactMap{$0}
.sink { index in
print("tap button in cell \(index.row)")
}.store(in: &cancellables)
return cell
}
and the cell is
class MyCell: UITableViewCell {
static let cellNibName = "MyCell"
static let celdaReuseIdentifier = "MyCellReuseIdentifier"
@IBOutlet weak var lbTitle: UILabel!
@IBOutlet weak var button: UIButton!
var index: IndexPath?
let tapButton = PassthroughSubject<IndexPath?, Never>()
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
@IBAction func tapButton(_ sender: Any) {
self.tapButton.send(index)
}
}
Thanks for your help