import UIKit
import CoreData
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
var notes = [NSManagedObject]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
// 获取管理对象上下文
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let managedContext = appDelegate.persistentContainer.viewContext
// 创建一个请求来检索“Note”实体中的所有数据
let fetchRequest = NSFetchRequest(entityName: "Note")
do {
let result = try managedContext.fetch(fetchRequest)
notes = result as! [NSManagedObject]
} catch let error as NSError {
print("Could not fetch. (error), (error.userInfo)")
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return notes.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let note = notes[indexPath.row]
cell.textLabel?.text = note.value(forKey: "text") as? String
return cell
}
@IBAction func addNote(_ sender: UIBarButtonItem) {
let alert = UIAlertController(title: "New Note", message: "Add a new note", preferredStyle: .alert)
let saveAction = UIAlertAction(title: "Save", style: .default) { [unowned self] action in
guard let textField = alert.textFields?.first, let text = textField.text else {
return
}
self.saveNote(withText: text)
self.tableView.reloadData()
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel)
alert.addTextField()
alert.addAction(saveAction)
alert.addAction(cancelAction)
present(alert, animated: true)
}
func saveNote(withText text: String) {
//。。。。。
代码太多,就不全贴了
结合以上的代码稍作调整估计就能运行
页面更新:2024-03-07
本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828
© CopyRight 2008-2024 All Rights Reserved. Powered By bs178.com 闽ICP备11008920号-3
闽公网安备35020302034844号