【发布时间】:2019-05-10 06:37:17
【问题描述】:
我正在编写一个购物车,一切似乎都运行良好,但我无法删除最后一行。
我可以删除但不能删除最后一行。
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。
我不知道怎么回事。
【问题讨论】:
-
我从复制和粘贴您的代码开始,因为没有错误和 2 个警告似乎是合理的,但我仍然崩溃
标签: ios swift uitableview tableview