在 SwiftUi 中的视图之间传递列表

问题描述

我正在自己制作一个待办事项列表应用程序以尝试熟悉 iOS 开发,但我遇到了这个问题:

我有一个单独的 View 链接,用于输入带有 TextField 的新任务。这是这个文件的代码:

import SwiftUI

struct AddTask: View {
     @State public var task : String = ""
     @State var isUrgent: Bool = false // this is irrelevant to this problem you can ignore it

    
    var body: some View {
        VStack {
            VStack(alignment: .leading) {
                Text("Add New Task")
                    .bold()
                    .font(/*@START_MENU_TOKEN@*/.title/*@END_MENU_TOKEN@*/)
                TextField("New Task...",text: $task)
                Toggle("Urgent",isOn: $isUrgent)
                    .padding(.vertical)
                Button("Add task",action: {"call some function here to get what is 
in the text field and pass back the taskList array in the Content View"})
               
                 
                
            }.padding()
            Spacer()
        }
    }
    
}


struct AddTask_Previews: PreviewProvider {
    static var previews: some View {
        AddTask()
    }
}

那么我需要将输入的任务变量插入到数组中以显示在我的主 ContentView 文件的列表中。

以下是供参考的 ContentView 文件:

import SwiftUI

struct ContentView: View {
    @State var taskList = ["go to the bakery"]
    
    struct AddButton<Destination : View>: View {

        var destination:  Destination

        var body: some View {
            NavigationLink(destination: self.destination) { Image(systemName: "plus") }
        }
    }
    
    var body: some View {
        VStack {
            NavigationView {
                List {
                    ForEach(self.taskList,id: \.self) {
                    item in Text(item)
                    }
                }.navigationTitle("Tasks")
                .navigationBarItems(trailing: HStack { AddButton(destination: AddTask())})
            }
            
        }
        
}
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
  }
}

我需要一个函数来获取在 TextField 中输入的任务,并将其传递回 ContentView 中的数组中,以便在 List 中为用户显示

-感谢您的帮助

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)