ios - 我无法在 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。
我不知道它是怎么回事。
解决方案
问题在这里:
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
}
如果您删除您的代码声称的最后一行,则现在没有任何部分。但是您不会删除任何部分,只会删除行。这会混淆表格视图并导致错误。
推荐阅读
- python - Kedro 找不到运行
- c - 如何在C中替换字符串中的字符?
- arrays - 直接地址表和数组是一回事吗?
- excel - 在代码中键入不匹配,但今天早些时候运行正常
- react-native - 如何在 React Native Web 中进行共享元素转换?
- c++ - 如何使用 qmake 在 linux 系统上将 boost lib 添加到 Qt?
- javascript - 当访问者使用我的无服务器站点和带有 xhReq.open("GET", "api-provider site com") 的 javascript 时,什么 IP 会看到 API 提供程序
- php - 网络抓取 - 数据在长轮询中重复
- intellij-idea - 开始使用 IntelliJ IDEA
- javascript - 反应js不导入css文件