从Swift 3中的UITableView删除一行?

inf*_*ouk 38 row 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()
    }
Run Code Online (Sandbox Code Playgroud)

ron*_*ory 100

适用于Swift 3Swift 4

使用UITableViewDataSource tableView(: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)
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 不,不要只是为了删除一行而调用`reloadData`.这是一种不好的做法. (17认同)
  • 对表视图的单个更改没有理由使用`begin/endUpdates`. (3认同)
  • 你是对的@rmaddy!更新了答案,并希望将其链接到之前提到过的其他答案,但遗憾的是删除了它 (2认同)

小智 22

首先,您需要添加此功能

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return true 
}
Run Code Online (Sandbox Code Playgroud)

那么你的功能是确定的,但没有必要的tableview重装数据的只是调用tableview.beingUpdatestableview.endUpdates

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
       print("Deleted")
       self.catNames.remove(at: indexPath.row)
       self.tableView.beginUpdates()
       self.tableView.deleteRows(at: [indexPath], with: .automatic)
       self.tableView.endUpdates() 
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 没有理由对表视图的单个更改使用 begin/endUpdates。 (2认同)

Jay*_*dip 9

Swift 4中尝试这个

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    func tableView(_ tableView: UITableView, commit editingStyle:   UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if (editingStyle == .delete) {
            arrStudentName.remove(at: indexPath.row)
            tableView.beginUpdates()
            tableView.deleteRows(at: [indexPath], with: .middle)
            tableView.endUpdates()
        }
    }
Run Code Online (Sandbox Code Playgroud)