我在TableViewCell上点击了一个segue,在另一个ViewController上有一个保存按钮,它在保存按钮上工作正常,但是当我点击后退按钮时它也会改变TableViewCell。我怎样才能丢弃变更?有NoteTableViewController和NoteViewController
TableViewController方法
tableView cellRowAt方法
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "NoteTableViewCell"
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! NoteTableViewCell
let note = notes[indexPath.row]
cell.noteLabel.text = note.note
return cell
}
TableViewController准备segue方法
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ShowDetail" {
let noteDetailViewController = segue.destination as! NoteViewController
if let selectedNoteCell = sender as? NoteTableViewCell {
let indexPath = tableView.indexPath(for: selectedNoteCell)!
let selectedNote = notes[indexPath.row]
noteDetailViewController.note = selectedNote
noteDetailViewController.oldNote = someNote
}
}
}
此方法用于保存数据,它连接到NoteViewController的saveButton
@IBAction func unwindToNoteList(sender: UIStoryboardSegue) {
if let sourceViewController = sender.source as? NoteViewController {
let note = sourceViewController.note
if note?.note != nil {
if let selectedIndexPath = tableView.indexPathForSelectedRow {
notes[selectedIndexPath.row] = note!
tableView.reloadRows(at: [selectedIndexPath], with: .none)
} else {
let newIndexPath = NSIndexPath(row: notes.count, section: 0)
notes.append(note!)
tableView.insertRows(at: [newIndexPath as IndexPath], with: .top)
}
saveNotes()
}
}
}
NoteViewController方法
准备segue
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if saveButton === sender as? UIBarButtonItem {
if let noteText = noteTextView.text {
note?.note = noteText
}
note?.toDate = remindDate
note?.image = photoImageView.image
} else {
note = oldNote
}
}
答案 0 :(得分:0)
通过实现NSObject copy()方法解决了问题。并将副本发送到NoteViewController。