【问题标题】:Delete rows from tableview using swift使用swift从tableview中删除行
【发布时间】:2020-05-27 06:13:18
【问题描述】:

我在我的应用程序上创建了一个表格视图,我想添加可以让用户删除表格视图中的行的选项。 我正在使用这个功能 h1 是我把它放在tableview 中的数组字符串。 我的错误是当我尝试删除 func editinstyle 中的行时

  var h1:[String] = ["one","two","three"]


 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        h1.count
}
 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {


        var cell = self.tableView.dequeueReusableCell(withIdentifier: "cell3", for: indexPath as IndexPath) as! TableView1

        cell.information.text = h1[indexPath.row]
}
  func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            print("Deleted")

            h1.remove(at: indexPath.row) //Remove element from your array
            print(h1)
            tableView.deleteRows(at: [indexPath], with: .fade)
        }
    }

当我尝试单击删除它时显示如下2020-02-11 20:43:35.803024+0200 TraniersApp[13314:401189] *** 由于未捕获的异常“NSInternalInconsistencyException”而终止应用程序,原因:“无效更新: 第 0 节中的行数无效。更新 (2) 后现有节中包含的行数必须等于更新 (2) 之前该节中包含的行数,加上或减去行数从该部分插入或删除(0 插入,1 删除),加上或减去移入或移出该部分的行数(0 移入,0 移出)。'

有人知道问题出在哪里吗?

【问题讨论】:

  • 您能否在调用remove(at:) 之前打印h1 以查看remove(at:) 是否实际执行任何操作?
  • 您显示的代码是正确的,但我怀疑这不是您的实际代码,因为屏幕截图中的输出不同。异常表明您的numberOfRows 函数存在问题。似乎还涉及另一个数组value
  • @Paulw11 谢谢,它有效

标签: ios swift iphone xcode uitableview


【解决方案1】:

怀疑这是一种竞争条件,可以通过在事务中执行 h1.remove() 和 tableView.deleteRows() 来解决(即在tableView.beginUpdates()tableView.endUpdates() 之间)。

    tableView.beginUpdates()
    h1.remove(at: indexPath.row) //Remove element from your array
    tableView.deleteRows(at: [indexPath], with: .fade)
    tableView.endUpdates()

【讨论】:

  • beginUpdates/endUpdates 对单个 insert/delete/move 操作完全没有影响。
  • @vadian 嗯。我站得更正了。我在此期间所做的其他事情似乎已经纠正了交易掩盖的真正错误。我能够毫无错误地删除交易。谢谢。
【解决方案2】:

定义“[indexPath]”。它变成 [IndexPath(row: indexPath.row, section: 0)]

tableView.deleteRows(at: [IndexPath(row: indexPath.row, section: 0)], with: .automatic)

同时调用表格视图中的特定部分

这将在函数之外工作

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath)

【讨论】:

    猜你喜欢
    • 2019-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多