swift - 在 Swift 中从 UITableView 中删除一行?

标签 swift uitableview row

我有一个名称表,我正在为它们创建一个滑动和删除函数,将它们从作为数组的名称变量中删除。

我选择了与 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()
    }
}

我是编码和学习 swift 的新手,我正在学习 swift 2 教程并使用 swift 3,因此在学习过程中遇到了一些问题,这是我一直坚持的一个问题。

最佳答案

适用于Swift 3Swift 4

使用 UITableViewDataSource tableView(:commit:forRowAt:) 方法,另请参阅此答案 here :

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)
  }
}

关于swift - 在 Swift 中从 UITableView 中删除一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59665447/

相关文章:

html - 如何在菜单页面中创建两行图标

ios - 从 ios 到 watchOS 的数据传输速率(发送或接收数据所需的时间)

ios - 未配置应用程序时在 Facebook 上分享

ios - UICollectionView 分页完成后会触发什么函数?

ios - Obj-C - 为字典中的第一个值过滤 TableView 中返回的数据?

Python Pandas 根据时间序列中缺失的顺序值添加行

javascript - 通过单击按钮添加行

ios - 不调用didSelectRowAtIndexPath获取UITableViewCell数据

ios - 加载 subview 触发根 ViewController

iphone - 当 UITabBar 选项卡更改时关闭 DetailController?