swift - 删除和编辑按钮未出现在 UITableViewCell 中

标签 swift core-data

我正在使用核心数据来保存任务列表的数据。输入的数据已保存,但删除和编辑选项未出现在选定的 TableViewCell 上。我进行了搜索,但无法获得此问题的充分答案。在这里,我给出了完整的代码。我在代码上的错误是什么...有人请帮助我吗??

class ToDoTableViewController: UITableViewController {    

  var listItems = [NSManagedObject]()

  override func viewDidLoad() {
    super.viewDidLoad()

    self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.add, target: self , action: #selector(ToDoTableViewController.addItem))

    navigationController?.navigationBar.barTintColor = UIColor(red: 220/255, green: 26/255, blue: 104/255, alpha: 1)
    tableView.backgroundView = UIImageView(image: UIImage(named: "settingsscreen.png"))

  }

// for adding items

  func addItem(){

    let alertController = UIAlertController(title: "To Do Tasks Lists!!!!", message: "Write Down...", preferredStyle: .alert)

    let confirmAction = UIAlertAction(title: "Confirm", style: UIAlertActionStyle.default, handler: ({
        (_) in

        if let field = alertController.textFields![0] as? UITextField {

            self.saveItem(itemToSave: (field.text!))
            self.tableView.reloadData()

        }
        }                        
    ))

    // for cancel alert controller

    let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil)

    alertController.addTextField(configurationHandler: ({
        (textField) in

        textField.placeholder = "Type in Something!!!!"
    }))

    alertController.addAction(confirmAction)
    alertController.addAction(cancelAction)

    self.present(alertController, animated: true, completion: nil)                
  }

  // to save the data on core data

  func saveItem(itemToSave : String){

    let appDelegate = UIApplication.shared.delegate as! AppDelegate

    let managedContext = appDelegate.managedObjectContext

    let entity = NSEntityDescription.entity(forEntityName: "ListEntity", in: managedContext)

    let item = NSManagedObject(entity: entity!, insertInto: managedContext)

    item.setValue(itemToSave, forKey: "item")

    do {
        try managedContext.save()
        listItems.append(item)
    }
    catch {

        print("Error")
    }                                
  }

  // to show the existing data on core data 

  override func viewWillAppear(_ animated: Bool) {
    let appDelegate = UIApplication.shared.delegate as! AppDelegate

    let managedContext = appDelegate.managedObjectContext

    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "ListEntity")

    do{
        let results = try managedContext.fetch(fetchRequest)

        listItems = results as! [NSManagedObject]
    }
    catch {
        print("Error")
    }                
  }

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

  }

  override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        listItems.remove(at: indexPath.row)
        tableView.reloadData()
    }               
  }

  override func setEditing(_ editing: Bool, animated: Bool) {
    super.setEditing(editing, animated: animated)
    tableView.reloadData()
  }

  override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return listItems.count
  }

  override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")! as UITableViewCell

    let item = listItems[indexPath.row]

    cell.textLabel?.text = item.value(forKey: "item") as! String?

    cell.backgroundColor = UIColor.clear
    return cell
  }
}

最佳答案

  • 首先删除整个方法setEditing。重新加载表格 View 会隐藏编辑/删除按钮。

  • 其次,您必须删除数据源数组中的对象,将其从托管对象上下文中删除,删除 TableView 中的行并保存上下文。 (之后不要调用 reloadData())。

    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
      if editingStyle == .delete {
         let appDelegate = UIApplication.shared.delegate as! AppDelegate
         let managedContext = appDelegate.managedObjectContext
         let objectToDelete = listItems[indexPath.row]
         listItems.remove(at: indexPath.row)
         managedContext.delete(objectToDelete)
         tableView.deleteRows(at: [indexPath], with: .fade)
         do {
            try managedContext.save()
         }
         catch {
            print("Error")
         }   
      }               
    }
    

关于swift - 删除和编辑按钮未出现在 UITableViewCell 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41298070/

相关文章:

ios - 我应该始终为我的模型使用 Core Data 吗?

ios - 更新 CoreData 对象无法正常工作

xcode - Swift:CoreData 库中的断点

ios - 为自定义 View 调用 NSBundle(使用 loadNibName)后访问 IBOutlet 的最佳方法

ios - iOS 11 的文件提供程序扩展中的项目

json - 如何将嵌套的 JSON 数组解析为 Codable 结构

swift - 当缩小标记在 Swift 4 中改变位置时

ios - 通过 UIImage 或 PHImageManager 调整图像大小

ios - 是否可以在 NSUserDefaults 中保存 NSManagedObject?

ios - UITableView indexPath 和最大可重用单元格数