ios - 无法删除 tableView 中的行
问题描述
我不断收到错误消息Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (2) must be equal to the number of rows contained in that section before the update (2)
。我有一个带有部分的 tableView,每个部分都包含一个表示行的字符串数组。我还尝试通过添加到 cellforRowAt 上的单元格的按钮进行删除。
extension RequestsViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myArr[section].myItems.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "RequestViewCell", for: indexPath) as! RequestViewCell
cell.description.text = "\(myArr[indexPath.section].myItems[indexPath.row])"
cell.declineBtn.tag = (indexPath.section * 100) + indexPath.row
cell.declineBtn.addTarget(self, action: #selector(declineRequest(sender:)), for: .touchUpInside)
cell.acceptBtn.tag = (indexPath.section * 100) + indexPath.row
cell.acceptBtn.addTarget(self, action: #selector(acceptRequest(sender:)), for: .touchUpInside)
return cell
}
然后如果按下拒绝 btn,则被调用的方法应该删除该行
@objc func declineRequest(sender: UIButton) {
let section = sender.tag / 100
let row = sender.tag % 100
let indexPath = IndexPath(row: row, section: section)
myArr.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
}
我尝试将协议方法也“提交编辑样式”添加到 .delete 和 canEditRowAt,但没有运气,因为我遇到了同样的错误。
解决方案
在declineRequest
你必须删除
myArr[section].myItems.remove(at: row)
如果您还想删除项目数组变为空的部分,请写入
// if there is one item left delete the section (including the row)
if myArr[section].myItems.count == 1 {
myArr.remove(at: section)
tableView.deleteSections([section], with: .fade)
} else { // otherwise delete the row
myArr[section].myItems.remove(at: row)
tableView.deleteRows(at: [indexPath], with: .fade)
}
推荐阅读
- mysql - 如何编写更新查询以清除数据库中的选定数据?
- python - 如何在不使用机器人应用程序的情况下发送不和谐的消息
- wordpress - 节点无法访问 Wordpress Docker 容器 (var/www/html)
- flutter - 使用 device_preview 包在我的颤振应用程序中引发错误
- c++ - 智能指针与原始指针的兼容性
- java - 使用 java 库上传到谷歌云存储时设置对象类型
- python - 将群组频道作为机器人离开
- ruby - 在您的 Gemfile 中列出的任何 gem 源中或在供应商/缓存中缓存的 gem 中找不到 gem 'xcode-install'
- python - 无法在 python 中获取产品 ID(Web 元素)
- sql - 单元格中的多行值