-2

I want to delete a table row by action from button in custom cell, using native tableView animations. Can someone help me please?

Grady
  • 174
  • 6
  • 21

1 Answers1

0

I Found a good solution, using a custom delegate and TableViewDataSource method!

I had to work with Protocol in my custom cell Class, like this:

protocol MyCellDelegate: class {
   func didDelete(cell: MyCell)
}

In my custom cell Class I made this:

class MyCell: UITableViewCell {

weak var delegate: MyCellDelegate?

@IBAction func deleteButtonTapped(_ sender: Any) {
     delegate?.didDelete(cell: self)
  }
}

In my ViewController I made the delegates and data source implementation:

extension ViewController: UITableViewDataSource {

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

        switch editingStyle {
        case .delete:
            tableView.beginUpdates()
            tableView.deleteRows(at:[indexPath], with: .fade)
            tableView.endUpdates()
        default:
            break
        }
    }
}

extension ViewController: MyCellDelegate {

    func didDelete(cell: MyCell) {

        guard let index = tableView.indexPath(for: cell) else {
            return
        }

        myArray?.remove(at: index.row)
        self.tableView(self.tableView, commit: .delete, forRowAt: index)
    }
}