I\'m using the code below to delete a row in my tableview. First I delete the object from my array and then from the tableview using this code:
let i = IndexPath
Problem
The problem in you case is the Tag you are setting on the Button , button Tag is not changed when you are deleting the Rows , as its the All Cell is not Reloaded.
i guess you are setting tag in cellforRowIndexpath
you try with putting tag on button in tableWillDisplayCell
or
the best way to do this is below .
Solution
you can get the IndexPath
in other way
Suppose if your view hierarchy is
UITableViewCell-> contentView -> button
in you button click method
if let cell = sender.superview?.superview as? UITableviewCell{
let indexPath = myTableView.indexPath(for: cell)
// Now delete the table cell
myArray.remove(at: indexPath.row)
myTableView.beginUpdates()
myTableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.left)
myTableView.endUpdates()
}
i hope this will work for you .
I was having this problem but none of the previous answers worked for me. If you run myTableView.reloadData()
within the same block as myTableView.deleteRows(at:with:)
, the animation doesn't run correctly.
You can run myTableView.performBatchUpdates(updates:completion:)
where you delete your row in the updates handler and reload your data in the completion handler. This way, the deletion animation runs properly and the index rows sync up.
myTableView.performBatchUpdates({
myTableView.deleteRows(at: [i], with: UITableViewRowAnimation.left)
}, completion: {finished in
myTableView.reloadData()
})
Use Apple's Code
The table view behaves the same way with reloading methods called inside an update block—the reload takes place with respect to the indexes of rows and sections before the animation block is executed. This behavior happens regardless of the ordering of the insertion, deletion, and reloading method calls.
[tv beginUpdates];
[tv deleteRowsAtIndexPaths:deleteIndexPaths withRowAnimation:UITableViewRowAnimationFade];
[tv endUpdates];
Any methods that insert or delete rows must be called inbetween tableView.beginUpdates()
and tableView.endUpdates()
. So your code must be:
let i = IndexPath(item: rowNum, section: 0)
myArray.remove(at: rowNum)
tableView.beginUpdates()
myTableView.deleteRows(at: [i], with: UITableViewRowAnimation.left)
tableView.endUpdates()
If you want to delete tableview row from a custom button action except for tableview commit editingStyle delegate or any tableview delegate method, you have to call tableview reloadData to populate with updated index value.