首页 > 解决方案 > 我无法在 Swift 中删除我的最后一个表格视图单元格

问题描述

我正在写一个购物车,一切似乎都运行良好,但我无法删除最后一行。

我可以删除但不能删除最后一行。

override func viewDidLoad() {
    super.viewDidLoad()

    createLineItems()
}

override func numberOfSections(in tableView: UITableView) -> Int {
    if lineItems.count == 0 {
        return 0
    } else {
        return 1
    }
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return lineItems.count
}

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    if(editingStyle == .delete) {
        lineItems.remove(at: indexPath.row)

        tableView.beginUpdates()

        let indPath = IndexPath(item: indexPath.row, section: 0 )

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

    }
}

func createLineItems() {
    lineItems = [LineItem]()

    lineItems.append(LineItem(frame:
        CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height),
                              index: 1)
        )


    lineItems.append(LineItem(frame:
        CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height),
                              index: 2)
    )

    lineItems.append(LineItem(frame:
        CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height),
                              index: 3)
    )

}

我得到的错误是打印出来:

由于未捕获的异常“NSInternalInconsistencyException”而终止应用程序,原因:“无效更新:无效的节数。更新后表视图中包含的节数(0)必须等于更新前表视图中包含的节数(1),加上或减去插入或删除的节数(0插入,0已删除)。

我读过了:

https://www.hackingwithswift.com/example-code/uikit/how-to-remove-cells-from-a-uitableview

以及我无法重新找到的其他页面。

我知道我必须先从数组中删除元素,然后再删除该行。

我知道我很确定我必须用 beginUpdates 和 endUpdates 包围我的行删除。

但我每次都得到那个错误。我已经尝试了 100 种不同的变体。

该错误表示行数必须比原始数少 1。

我不知道它是怎么回事。

标签: iosswiftuitableviewtableview

解决方案


问题在这里:

override func numberOfSections(in tableView: UITableView) -> Int {
    if lineItems.count == 0 {
        return 0
    } else {
        return 1
    }
}

它应该是:

override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

如果您删除您的代码声称的最后一行,则现在没有任何部分。但是您不会删除任何部分,只会删除行。这会混淆表格视图并导致错误。


推荐阅读