如何使SwiftUI按钮将新元素添加到数组并执行导航转换(如NavigationLink)?

时间:2019-08-01 17:37:52

标签: swiftui

我正在尝试完成一些在UIKit中但在SwiftUI中非常简单的事情。我的NoteList视图基本上在一个List中显示一个Notes数组。轻按“列表”中的一个便笺,即可将便笺添加到导航堆栈中,从而打开带有该便笺的便笺明细。这部分有效。但是我也想在导航栏中有一个“新笔记”按钮。我添加了一个叫做newNoteButton的东西。当用户按下newNoteButton时,我希望将新注释添加到注释数组中,并且我希望应用程序通过将该注释添加到导航堆栈中来打开具有该注释的NoteDetail。

到目前为止,我了解我可以创建一个将注释添加到数组的Button,或者可以创建一个将NoteDetail添加到导航堆栈的NavigationLink。但我还没有找到一种同时做这两种方法的方法。而且,我似乎还无法通过在SwiftUI上搜索教程和书籍来找到解决方案。

到目前为止,这是我的代码。任何帮助将不胜感激。

struct NoteList: View {

  @State var notes: [Note] = [
    Note(id: UUID(), content: "Some note"),
    Note(id: UUID(), content: "Some other note")
  ]

  var newNoteButton: some View {
    Button(action: {
      let note = Note(id: UUID(), content: "New Note")
      self.notes.append(note)
      NoteDetail(note: note) // Obviously this doesn't work but I want to add a NoteDetail to the navigation stack with the newly created note
    }) {
      Image(systemName: "plus")
        .imageScale(.large)
        .accessibility(label: Text("New Note"))
    }
  }

  var body: some View {
    NavigationView {
      List {
        ForEach(notes) { note in
          NavigationLink(destination: NoteDetail(note: note)) {
            Text(note.content)
          }
        }
      }
      .navigationBarTitle(Text("Notes"), displayMode: .large)
      .navigationBarItems(trailing: newNoteButton)
    }
  }

}

0 个答案:

没有答案
相关问题