在 Swift 中从 UITableView 中删除一行? [英] Deleting a Row from a UITableView in Swift?

查看:45
本文介绍了在 Swift 中从 UITableView 中删除一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a table of names and I am making a swipe and delete function for them which removes them from a names variable which is an array.

我在 xcode 中选择了与教程最相似的函数并填写了它们,但是当我单击删除按钮时,我的应用程序随机崩溃.这是我的删除按钮代码:

I selected the functions which most closely resembled the tutorial inside xcode and filled them out, but my app crashes randomly when I click the delete button. Here is my code for the delete button:

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,所以我在学习时遇到了一些问题,这是我一直坚持的问题.

I'm new to coding and learning swift, I am following a tutorial for swift 2 and working with swift 3 so there are a few issues I have when following along, this being one I'm properly stuck on.

推荐答案

适用于 Swift 3Swift 4

使用 UITableViewDataSource tableView(:commit:forRowAt:) 方法,另见此答案这里一个>:

Use the UITableViewDataSource tableView(:commit:forRowAt:) method, see also this answer 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 中从 UITableView 中删除一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆