0

I'm dynamically adding a custom cell to a UITableView and I'd like each cell to have a button which can remove that cell from the data structure and reload the views.

didSelectRowAt indexPath is able to remove the element from my data structure by using indexPath.section and indexPath.row, and then reload the table, but how can I do this on touch of a button within the cell?

It was suggested to move the logic to the button's touchUpInside, but how can I do that? And how can I receive the section and row of the cell that the button was pressed in to know which element to remove from the data structure?

Gimme the 411
  • 994
  • 9
  • 25
  • Create a button on each cell set the button tag as indexPath.row. Now in the button touchUpInside action you will get the button as sender and get the button tag. use the tag to handle your data. – vivekDas Aug 07 '18 at 06:10

1 Answers1

0

You can store indexPath variable in a custom cell object and call function on controller. You need to set indexPath and delegate in cellForRow(at:) function.

protocol CellButtonProtocol: class {
    func cellButtonClicked(indexPath: IndexPath?)
}
class CustomCell: UITableViewCell {
    weak var delegate: CellButtonProtocol?
    var indexPath: IndexPath?

    func buttonClick() {
        delegate?.cellButtonClicked(indexPath: indexPath)
    }
}
ymutlu
  • 6,585
  • 4
  • 35
  • 47