Невозможно удалить строку в tableView - PullRequest
0 голосов
/ 21 января 2020

Я получаю сообщение об ошибке 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). У меня есть tableView с разделами, и каждый раздел содержит массив строк, представляющих строку. Я также пытаюсь сделать удаление через кнопку, которую я добавляю в ячейку на 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
    }

, а затем вызываемый метод должен удалить строку, если нажата клавиша сброса

@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)
    }

Я пытался добавить методы протокола 'commit editstyle' к .delete и canEditRowAt, но без везения, поскольку я получаю ту же ошибку.

1 Ответ

1 голос
/ 21 января 2020

В declineRequest необходимо удалить

myArr[section].myItems.remove(at: row)

Если вы хотите удалить также раздел, если массив элементов становится пустым, напишите

// 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)
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...