【发布时间】:2021-05-17 16:06:54
【问题描述】:
我正在尝试创建一个日记应用程序,并有一个包含条目列表的表格视图。添加新按钮可添加新记录,单击表中的行可编辑记录。 Add new 和 Edit 都将您带到一个不同的视图控制器,该控制器都设置在 Navigation 控制器中。
我已经完成了大部分工作,除了更新记录时遇到问题。编辑时,它会添加一条新记录而不是更新旧记录(使用当前条目数据)。在转移到另一个 vc 之前,我使用了一个对话框。
查看代码看起来是因为我没有通过索引路径。有谁知道我如何做到这一点?我当前的代码如下。有任何问题请告诉我。
添加新记录
@IBAction func addNew(_ sender: Any) {
let newEntry = DiaryEntry(context: self.context)
newEntry.entry = self.entryEntry.text //The Main Entry
newEntry.date = Date() //The Date (Auto)
newEntry.rating = Int16(self.ratingInt) //The Rating
newEntry.entryName = self.entryName.text //The Entry Name
do{
try self.context.save()
dismiss(animated: true, completion: nil)
//print("Saved correctly")
}catch{
print(error)
}
self.fetchData()
}
更新当前记录
@IBAction func updateRecord(_ sender: Any) {
let newEntry = DiaryEntry(context: self.context)
newEntry.entry = self.entryEntry.text //The Main Entry
newEntry.date = Date() //The Date (Auto)
newEntry.rating = Int16(self.ratingInt) //The Rating
newEntry.entryName = self.entryName.text //The Entry Name
do{
try self.context.save()
dismiss(animated: true, completion: nil)
//print("Saved correctly")
}catch{
print(error)
}
self.fetchData()
}
据我了解,我认为问题出在 newEntry 上下文部分。不过我有点失落。
这就是我将它放在警报框中时的代码(并且有效)
let entry = self.items![indexPath.row]
let alert = UIAlertController(title: "Edit Entry", message: "Edit an entry to your Diary", preferredStyle: .alert)
alert.addTextField()
let textfield = alert.textFields![0]
textfield.text = entry.entry
let saveBtn = UIAlertAction(title: "Save", style: .default) { (action) in
entry.entry = textfield.text
do {
try self.context.save()
}catch{
print(error)
}
self.fetchData()
}
let cancelBtn = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alert.addAction(saveBtn)
alert.addAction(cancelBtn)
self.present(alert, animated: true, completion: nil)
我知道这很简单,但我无法解决。
谢谢
【问题讨论】:
标签: ios swift xcode uiviewcontroller uinavigationcontroller