- 繼續問UITableView的用法
- Core data存儲資料的方法
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<NSFetchRequestResult>(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) {
//。。。。。
代碼太多,就不全貼了
- 接下來建立筆記類
- 在 UITableView 的資料源方法中,使用筆記資料填充 UITableViewCell。
- 實作編輯功能,允許使用者添加、編輯和删除筆記
結合以上的代碼稍作調整估計就能運作