ios - 滑动删除函数插入,包括核心数据
问题描述
我正在尝试做一个简单的名单应用程序。我已经观看了这个视频并复制了所有内容(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()
}
}
解决方案
您只是从本地数组中删除该项目,您需要在删除后保留更改。
推荐阅读
- typescript - 我可以访问 TypeScript 中类定义之外的私有变量吗?
- java - 我如何使用 trim() 方法来完成这项工作?我需要读取 txt 文件,同时忽略以“//”开头的空行和行
- latex - 使用列表颜色格式中断的可破坏 tcolorbox
- lua - 如何打印lua的计算结果
- c++ - 擦除在while循环中迭代的元素
- python - 通过 python-docx 转录 Word docx 文件以修改字体和字体大小,
- java - 将mysql查询转换为休眠条件
- mysql - SQL选择查询哈希密码错误
- r - JAGS 无法识别存储在 R 全局环境中的值
- java - 使用 findViewById 初始化对象后直接出现 java.lang.NullPointerException