ios - 我无法在 Swift 中删除我的最后一个表格 View 单元格

标签 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)
    )

}

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

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of sections. The number of sections contained in the table view after the update (0) must be equal to the number of sections contained in the table view before the update (1), plus or minus the number of sections inserted or deleted (0 inserted, 0 deleted).'

我已阅读:

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

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

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

我知道我很确定我必须用 beginUpdates 和 endUpdates。

但我每次都会遇到这个错误。我尝试了 100 种不同的变体。

错误表明行数必须比原始数字少 1。

我不知道怎么会这样。

最佳答案

问题在这里:

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
}

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

关于ios - 我无法在 Swift 中删除我的最后一个表格 View 单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56072030/

相关文章:

ios - 如何检查 HealthKit 是否被授权

javascript - 分析 iPad Air 2 前端 (js) 性能问题的策略

objective-c - KVO 不适用于类属性

ios - 在 swift 类中使用 Pushkit 而不是 AppDelegate

ios - 调用 'becomeFirstResponder()' 的结果是 UITableView 中未使用的 UITextField

iphone - 如何实现多列、横向滚动的UITableView

ios - Swift - 在 iOS 中查找 4 位整数的反对数

ios - 如何在某个 CGPoint 处创建 UIView?

ios - 即时更改模糊效果样式

ios - 如何在 swift 中的索引路径委托(delegate)的行的单元格中加载自定义表格 View 单元格