Reputation: 175
I keep getting an error saying Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (2) must be equal to the number of rows contained in that section before the update (2)
. I have a tableView with sections and each sections contains an array of strings representing the row. I am also trying to do the delete through a button which I am adding to the cell on cellforRowAt.
extension RequestsViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myArr[section].myItems.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "RequestViewCell", for: indexPath) as! RequestViewCell
cell.description.text = "\(myArr[indexPath.section].myItems[indexPath.row])"
cell.declineBtn.tag = (indexPath.section * 100) + indexPath.row
cell.declineBtn.addTarget(self, action: #selector(declineRequest(sender:)), for: .touchUpInside)
cell.acceptBtn.tag = (indexPath.section * 100) + indexPath.row
cell.acceptBtn.addTarget(self, action: #selector(acceptRequest(sender:)), for: .touchUpInside)
return cell
}
and then the method being called is supposed to remove the row if decline btn is pressed
@objc func declineRequest(sender: UIButton) {
let section = sender.tag / 100
let row = sender.tag % 100
let indexPath = IndexPath(row: row, section: section)
myArr.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
}
I tried to add the protocol methods too 'commit editingstyle' to .delete and canEditRowAt, but with no luck as I get the same error.
Upvotes: 0
Views: 50
Reputation: 285059
In declineRequest
you have to delete
myArr[section].myItems.remove(at: row)
If you want to remove also the section if the items array becomes empty write
// if there is one item left delete the section (including the row)
if myArr[section].myItems.count == 1 {
myArr.remove(at: section)
tableView.deleteSections([section], with: .fade)
} else { // otherwise delete the row
myArr[section].myItems.remove(at: row)
tableView.deleteRows(at: [indexPath], with: .fade)
}
Upvotes: 1