关闭屏幕后列表未更新

时间:2020-10-29 09:12:02

标签: swift swiftui swiftui-list

这是我当前的代码

Content.swift

struct ContentView: View {
    var taskStore : TaskStore
    @State var modalIsPresented = false
    
    var body: some View {
        NavigationView {
            List(taskStore.tasks){ task in
                Text(task.name)
            }.navigationTitle("Tasks")
            .navigationBarItems(trailing: Button(action: {
                self.modalIsPresented = true
            }) {
                Image(systemName: "plus")
            })
        }.sheet(isPresented: $modalIsPresented){
            NewTaskView(taskStore: self.taskStore)
        }
    }
}

TaskStore.swift

class TaskStore {
    var tasks = [
        "Code The App",
        "Book an escape room",
    ].map{  Task(name: $0)}
}

newTask.swift

struct NewTaskView: View {
    var taskStore : TaskStore
    @State var text = ""
    
    @Environment (\.presentationMode) var presentationMode
    
    var body: some View {
        Form{
            TextField("Task Name", text: $text)
            Button("Add"){
                self.taskStore.tasks.append(
                    Task(name: self.text)
                )
                print(taskStore.tasks)
                self.presentationMode.wrappedValue.dismiss()
            }.disabled(text.isEmpty)
        }
    }
}

但是,当我关闭列表时,不会更新,但是当我打印值时,taskStore.name会更新

不确定是什么问题

1 个答案:

答案 0 :(得分:0)

要观察TaskStore任务的变化,请按照如下所示将类符合ObservableObject协议:

class TaskStore : ObservableObject{
  @Published var tasks = [
      "Code The App",
      "Book an escape room",
   ] .map{  Task(id: $0, name: $0)}
}

并如下所示更新ContentView中taskStore的声明:

struct ContentView: View {
     @ObservedObject var taskStore : TaskStore

要了解有关Observable的更多信息,请参阅:https://medium.com/cleansoftware/what-is-the-observableobject-protocol-in-swifts-combine-b6ad3102ccd4