首页 > 解决方案 > 滑动删除函数插入,包括核心数据

问题描述

我正在尝试做一个简单的名单应用程序。我已经观看了这个视频并复制了所有内容(https://www.youtube.com/watch?v=tP4OGvIRUC4)我现在想添加一个滑动删除功能。它按照我希望的方式工作,但是当我关闭并重新打开应用程序时,它会像以前一样。我尝试了不同的东西,但没有奏效。

有人有什么想法吗?

来自瑞士的问候

这是我的视图控制器:

import UIKit
import CoreData

class ViewController: UIViewController {

@IBOutlet weak var tableView: UITableView!

    var people = [Person]()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        let fetchRequest: NSFetchRequest<Person> = Person.fetchRequest()

        do {
          let people = try PersistenceServce.context.fetch(fetchRequest)
            self.people = people
            self.tableView.reloadData()
        }catch{}
    }

    @IBAction func onPlusTapped() {
        let alert = UIAlertController(title: "Add name", message: nil, preferredStyle: .alert)
        alert.addTextField { (textField) in
            textField.placeholder = "Name"

        }
        let action = UIAlertAction(title: "Add", style: .default) { (_) in
            let name = alert.textFields!.first!.text!
            let person = Person(context: PersistenceServce.context)
            person.name = name
            PersistenceServce.saveContext()
            self.people.append(person)
            self.tableView.reloadData()

        }
        alert.addAction(action)
        present(alert, animated: true, completion: nil)
    }
}

extension ViewController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
         return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return people.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .subtitle, reuseIdentifier: nil)
        cell.textLabel?.text = people[indexPath.row].name
        return cell
    }
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {

        guard editingStyle == UITableViewCell.EditingStyle.delete else { return }
        people.remove(at: indexPath.row)

        tableView.deleteRows(at: [indexPath], with: .automatic)
        self.tableView.reloadData()
    }
}

标签: iosswiftcore-datadelete-row

解决方案


您只是从本地数组中删除该项目,您需要在删除后保留更改。


推荐阅读