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

标签 ios swift swift3

我是 Swift 3 的初学者。我有一个 TableView ,用户可以删除 TableView 单元格。现在我希望用户能够更改单元格的内容。我有一个包含四个名称 ["Stremmel"、"Emma"、"Sam"、"Daisy"] 的数组,我希望用户能够对 George 说编辑 Stremmel。
我搜索了文档或类似的问题,它们可以帮助我想出一种方法,但我变得更加困惑。有人可以给我一些帮助吗!!谢谢你。这是我的表格 View :

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


}

最佳答案

如果您还想显示带有删除按钮的编辑按钮,那么您需要使用canEditRowAt 方法而不是commit editingStyle 方法来实现editActionsForRowAt 方法。

之后使用 editActionsForRowAt 显示 AlertControllertextField 并更新其值并重新加载该行。因此,从您的代码中删除或注释 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]
}

关于ios - 如何在 Swift 3 中编辑表格单元格的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43402434/

相关文章:

ios - 使用类在 Swift3 中自定义按钮及其突出显示状态

swift - setTitle(_ title : String? , for state : UIControlState) where is . 正常状态?

swift - 在 Xcode 8.0 Swift 3.0 上的接口(interface) Controller 之间传递数据

ios - 如何在带有图像的 SwiftUI 中使用 Bundle

ios - 从 iOS 设备播放视频文件

iphone - 从我的应用程序中启动时,字符被邮件应用程序切断

ios - Swift Regular Expression create For Url "www"not for "http"for valid URL

ios - AgoraKit 无法发送 `userinfo` 给远程用户

ios - 无法在路径中打开 Realm

ios - UICollectionViewCell 中的渐变 BG