user10375884
user10375884

Reputation:

Unable to delete row from table view

I have a table view with a certain number of rows. With a button on the same ViewController, I want to pop out one of the tableView rows. However, I am unable to do so. Note that I am not using editing style of table view but using a button on the same ViewController to delete a row from the tableView.

func postAction() {
        postTable.deleteRows(at: [IndexPath(row: 0, section: 0)] , with: .fade)
}

However this results in crash. I am not sure why is this happening and how I should correct this. I intend to delete the first row from the only section here in the tableView (postTable)

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0.
The number of rows contained in an existing section after the update (3) must be equal to the number of rows contained in that section before the update (3), plus or minus the number of rows inserted or deleted from that section (0 inserted, 1 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'

My code:

    postTable.delegate = self
    postTable.dataSource = self

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
      return 3
    }

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

            let cell = JobPostCellView(style: UITableViewCellStyle.default , reuseIdentifier: "PostCell")
            cell.delegate = self
            cell.name = arr[indexPath.row]
            return cell
    }

Upvotes: 1

Views: 93

Answers (1)

Devil Decoder
Devil Decoder

Reputation: 1086

try this

func postAction() {
    let indexPath = IndexPath(row: 0, section: 0)
    yourmodel.remove(at: indexPath.row)//update your model also here
    postTable.deleteRows(at: [indexPath] , with: .fade)
}

this may be happenig because you tableview row is not matching with the returning rows from number of rows in section method of your data source

for example

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 10
}

if you are returning 10 in your numberOfRowsInSection then there will be 10 rows in table

now you are deleting 1 row from it so the rows will be 9 but your numberOfRowsInSection method still returning 10 so this will create inconsistency so you have to update your count in numberOfRowsInSection section to return 9

and if you are using dynamic array than you have to delete it from your array also like in answer

Upvotes: 2

Related Questions