如何在Swift 3中编辑表格单元格的内容

D.M*_*ses 3 ios swift swift3

我是Swift 3的初学者.我有一个表视图,用户可以删除表视图单元格.现在我希望用户能够更改单元格的内容.我有一个包含四个名字的数组["Stremmel","Emma","Sam","Daisy"],我希望用户能够说Stremmel到George.
我搜索了文档或类似的问题,可以帮助我找到一种方法,但我更困惑.有人可以请我帮忙!! 谢谢.这是我的表格视图:

import UIKit
var list = ["Stremmel" , "Emma" , "Sam" , "Daisy"]
class ViewController: UITableViewController {

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
   return list.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
{
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
    cell.textLabel?.text = list[indexPath.row]
    return cell
}
override func tableView(_ tableView: UITableView, commit editingStyle:  UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

if editingStyle == UITableViewCellEditingStyle.delete
{
     list.remove(at: indexPath.row)
     tableView.reloadData()
}


}
Run Code Online (Sandbox Code Playgroud)

Nir*_*v D 10

如果您还想使用"删除"按钮显示"编辑"按钮,则需要editActionsForRowAt使用canEditRowAt方法而不是实现方法commit editingStyle.

之后使用editActionsForRowAtshow AlertControllerwith textField并更新其值并重新加载行.因此,commit editingStyle从代码中删除或注释该方法,并添加以下两种方法.

override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return true
}

override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    let editAction = UITableViewRowAction(style: .default, title: "Edit", handler: { (action, indexPath) in
        let alert = UIAlertController(title: "", message: "Edit list item", preferredStyle: .alert)
        alert.addTextField(configurationHandler: { (textField) in
            textField.text = self.list[indexPath.row]
        })
        alert.addAction(UIAlertAction(title: "Update", style: .default, handler: { (updateAction) in
            self.list[indexPath.row] = alert.textFields!.first!.text!
            self.tableView.reloadRows(at: [indexPath], with: .fade)
        }))
        alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
        self.present(alert, animated: false)
    })

    let deleteAction = UITableViewRowAction(style: .default, title: "Delete", handler: { (action, indexPath) in
        self.list.remove(at: indexPath.row)
        tableView.reloadData()
    })

    return [deleteAction, editAction]
}
Run Code Online (Sandbox Code Playgroud)