小编典典

在Swift 3中从UITableView删除行?

swift

我是Swift编码和学习的新手,我正在关注swift 2的教程并使用swift 3,因此在继续学习时会遇到一些问题,这是我一直坚持的问题。

我有一张名字表,我正在为它们做一个滑动和删除功能,将它们从一个名称变量中删除,该变量是一个数组。我选择了与xcode内的教程最相似的函数并将其填充,但是当我单击删除按钮时,我的应用程序会随机崩溃。这是我的删除按钮代码…

    func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {

    let deleteAction = UITableViewRowAction(style: .destructive, title: "Delete") { (rowAction: UITableViewRowAction, indexPath: IndexPath) -> Void in

        print("Deleted")

        self.catNames.remove(at: indexPath.row)
        self.tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
        self.tableView.reloadData()
    }

阅读 333

收藏
2020-07-07

共1个答案

小编典典

适用于 Swift 3Swift 4

使用UITableViewDataSourcetableView(:commit:forRowAt:)方法

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
  if editingStyle == .delete {
    print("Deleted")

    self.catNames.remove(at: indexPath.row)
    self.tableView.deleteRows(at: [indexPath], with: .automatic)
  }
}
2020-07-07