0

Is it possible to reload a table view from within a table view cell's controller? I have a custom delete button in my table view cells, and I would like the cell to be deleted from within the cell's delete button's IBAction function.

In my case, it can either be done by allowing the cell to tell the table view to reload, or by allowing the cell to delete itself.

I understand how to reload the table view from within the table view's view controller but not from within the cell. I can't find any syntax for the cell to self-delete or reload its parent table view. Any help would be greatly appreciated.

code_relic
  • 39
  • 8
  • See the following (It's in Objective-C but it's the type of solution you want): [How to delete UITableViewCell from within same cell?](https://stackoverflow.com/questions/24652812/how-to-delete-uitableviewcell-from-within-same-cell) – HangarRash Dec 26 '22 at 23:58
  • The cell can't do it directly. You can use a delegation or closure from your cell back to your view controller. Your cell should just be a view and shouldn't know anything about your data model or business logic – Paulw11 Dec 27 '22 at 01:20
  • Calling `reloadData` after deleting an item causes unnecessary expense. There is `deleteRows(at:with:)` to remove one or multiple rows animated. – vadian Dec 28 '22 at 08:23

1 Answers1

0

If you are using storyboards then you can create the button's IBAction directly in your controller, if you are using nibs then you can simply add a tap gesture on your delete button while dequeuing your cell.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell =  dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCell
    // if you have created a cell using nibs. if you are using storyboards use IBAction instead.
    cell.deleteButton.addGestureRecognizer(UITapGestureRecognizer(target: self, #selector(handleButtonTap))
    //set the button tag equal to the cell row
    cell.deleteButton.tag = indexPath.row
    return cell
}

And in your IBAction for the delete button

@IBAction func handleDeleteButtonTap(_ sender: Any) {
    guard let button = sender as? UIButton else {
        return
    }
    let index = button.tag
    // delete item at index
    // then
    tableView.reloadData()
}

And if you used a gesture recognizer instead, then use this method

@objc func handleDeleteButtonTap(_ sender: UITapGestureRecognizer) {
    guard let index = sender.view?.tag else {
        return
    }
    // delete item at index
    // then
    tableView.reloadData()
}
A. Basit
  • 81
  • 3