MyTableviewController
var animalNameArray = ["cat","dog","lion"]
override func viewDidLoad() {
super.viewDidLoad()
tableview.delegate = self
tableview.dataSource = self
self.cancelButton.isEnabled = false
}
@IBAction func editButtonAtNavigationBar(_ sender: UIBarButtonItem) {
self.cancelButton.isEnabled = true
self.tableview.isEditing = !self.tableview.isEditing
sender.title = (self.tableview.isEditing) ? "Done" : "Edit"
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
animalNameArray.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let remove = UITableViewRowAction(style: .default, title: " ") { action, indexPath in
}
remove.backgroundColor = UIColor(patternImage: UIImage(named: "delete")!)
return [remove]
}
//conditional Rearranging the table view cells
func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
return true
}
}
我想放图像(垃圾箱)而不是文本,图像正在显示,但在尝试删除行时没有发生删除操作。我不知道我做错了什么。如何删除我的表视图行?有人可以帮我吗?提前谢谢。
您应该删除在 indexPatheditActionsForRowAt
中传递的单元格,如下所示:
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let remove = UITableViewRowAction(style: .default, title: " ") { action, indexPath in
tableView.beginUpdates()
tableView.deleteRows(at: [IndexPath(row: index, section: 0)], with: .left)
tableView.endUpdates()
}
remove.backgroundColor = UIColor(patternImage: UIImage(named: "delete")!)
return [remove]
}
它将删除该行,但它与数组中的数据不一致。您还可以从数组中的特定索引处删除项,然后调用tableView.reloadData()
从表视图中删除行后,您需要重新加载rows
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let remove = UITableViewRowAction(style: .default, title: " ") { action, indexPath in
tableView.deleteRows(at: [IndexPath(row: index, section: 0)], with: .left)
self.tableView.reloadRows(at: [IndexPath], with: .fade)
}
remove.backgroundColor = UIColor(patternImage: UIImage(named: "delete")!)
return [remove]
}