2017-04-13 108 views
0

我是Swift 3的初学者。我有一个表格视图,用户可以删除表格视图单元格。现在我希望用户能够更改单元格的内容。我有一个包含四个名字[“Stremmel”,“Emma”,“Sam”,“Daisy”]的数组,并且我希望用户能够向George编辑Stremmel。
我搜索了文档或类似的问题,可以帮助我找到一种方式来做到这一点,但我更加困惑。有人可以给我提供一些帮助!谢谢。这里是我的表视图:如何在Swift 3中编辑表格单元格的内容

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


} 

回答

2

如果您想要使用删除按钮显示编辑按钮,则需要使用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] 
} 
+0

我能问一下第一个是什么意思? (self.list [indexPath.row] = alert.textFields!.first!.text!) –

+0

@ D.Moses AlertController有['textFields'](https://developer.apple.com/reference/uikit/uialertcontroller/ 1620104-textfields)类型为[[UItextField]]的属性,我们在alert中有一个textfield,所以我们使用'textFields'数组的第一个属性来访问它。 –

+1

这非常有帮助。感谢您的澄清。 –

0

通常创建UITableViewController()类时,你应该有一些模板代码,提供了一个编辑按钮和删除功能(应包括在编辑按钮)!只需取消注释,它应该可以访问!

或者您可以在viewDidLoad()函数中调用self.editButtonItem()

对不起我的英文不好,我希望能回答你的问题!

+0

对不起,我不太了解你的答案,但我感谢你的帮助。 –

相关问题