How to delete table view row from custom cell?

时间:2016-10-20 18:50:37

标签: ios swift xcode uitableview tableviewcell

I have a custom table view cell with two buttons. If either one is pressed, I want the table view to delete the row. I already know the code for that:

myArray.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)

I just would like to call this from my custom cell. I have it set up like so:

@IBAction func handleDecline(sender: AnyObject)
{
    // Remove table view row 
}

@IBAction func handleApprove(sender: AnyObject)
{
    // Remove table view row
}

How would I go about doing that?

1 个答案:

答案 0 :(得分:1)

You should not handle deletion of a cell from the cell itself. It violates MVC pattern. Events should be delegated to the view controller and handled there with deleteRows method like this:

tableView.deleteRows(at: [indexPath], with: .fade)

Also tableView's dataSource must be updated accordingly, otherwise app will crash.

Here you can find an example of how you can delegate an event from cell to view controller