I'm making a ToDo list app on my own to try to get familiar with iOS development and there's this one problem I'm having:
I have a separate View
linked to enter in a new task with a TextField
. Here's the code for this file:
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()
}
}
So what I need to take the task variable entered and insert it into the array to be displayed in the list in my main ContentView
file.
Here's the ContentView
file for reference:
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()
}
}
}
I need a function to take the task entered in the TextField
, and pass it back in the array in the ContentView
to be displayed in the List
for the user
-thanks for the help
You can add a closure property in your
AddTask
as a callback when the user tapsAdd Task
. Just like this:Then, in
ContentView
:@jnpdx provides a good solution by passing
Binding
of taskList toAddTask
. But I thinkAddTask
is used to add a new task so it should only focus on The New Task instead of full taskList.