【发布时间】:2021-05-02 01:16:04
【问题描述】:
我正在尝试克隆 iOS Note App。我在将数据从 Viewcontroller 传递回另一个 Tableviewcontroller 时遇到问题。 (这里从 EditorViewController 到 MainViewController)
我有一个带有 Text 和 Date 属性的 Note 类。
class Note: Codable {
var text: String
var modificationDate: Date
init(text: String, modificationDate: Date) {
self.text = text
self.modificationDate = modificationDate
}
}
表格视图:
class MainViewController: UITableViewController {
var notes = [Note]()
@objc func createNoteTapped(noteIndex: Int) {
if let vc = storyboard?.instantiateViewController(identifier: "EditorViewController") as? EditorViewController {
navigationController?.pushViewController(vc, animated: true)
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return notes.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
...
}
}
和 ViewController 应该将 Note 数据发送回上面的 tableview。
class EditorViewController: UIViewController {
var notes: [Note]!
var noteIndex: Int!
@IBOutlet var textView: UITextView!
func setParameters(notes: [Note], noteIndex: Int) {
self.notes = notes
self.noteIndex = noteIndex
notes.append(notes[noteIndex])
}
@objc func saveNote() {
...
}
}
在 EditorViewcontroller 中,我有一个 textview ,我想将其中的文本保存为 Note 文本,并在点击 saveNote 时将该 Note 加载到 TableView 中。我真的被困住了,我应该如何编写 saveNote 函数来做到这一点?感谢您的帮助。
【问题讨论】:
-
委托模式? EditorViewController 应该有一个具有类似 func noteCreated(note: Note) 方法的委托,并且您需要将 ViewController 作为 EditorViewController 委托传递,我认为这个答案在几个问题中得到了回答
-
感谢@ReinierMelian,问题是它在展开 Optional value 时给出了 Unexpectedly found nil 的错误。似乎它没有将Textview保存到Note中,如何避免这种情况?我应该像
notes.append(Note(text: "AAA", modificationDate: Date()))这样初始化它吗? -
您想将notes数组或仅一个数组从编辑器传递给ViewController?
-
@ReinierMelian 将一个数组传回 Tableview。
-
那么你需要将你新创建的笔记对象附加到你的数组中,然后你需要通过
func updatedNotes(notes: [Note])将它传递给委托
标签: ios swift xcode uitableview tableview