我无法删除Swift

时间:2019-05-10 06:37:18

标签: ios swift uitableview tableview

我正在写一个购物车,一切似乎都正常,但是我不能删除最后一行。

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

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。

我不知道怎么回事。

1 个答案:

答案 0 :(得分:3)

问题在这里:

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
}

如果您删除最后一行,则代码将声明现在没有任何节。但是您没有删除任何节,仅删除行。这会混淆表视图并导致错误。

相关问题