我有三个文件:AddAssignment、ViewAssignment 和 Task。单击 AddAssignment.swift 上的一个按钮,该按钮成功地将表单数据附加到 Task.swift 内部的一个数组中。
但是,在文件 AddAssignment.swift 中,该数组中的每个项目都通过循环传递,视图无法使用新附加的数据进行更新。
AddAssignment.swift
import SwiftUI
struct AddAssignment: View {
@State var taskName = ""
@State var dueDate = ""
@State var subject = ""
@State var weighting = ""
@State var totalMarks = ""
@State var buttonClicked = false
var body: some View {
NavigationView {
VStack {
HStack { // Titling
Spacer()
Text("Add New Task")
.font(.headline)
.scaleEffect(2.0)
Spacer()
Image(systemName: "plus.square.fill")
.scaleEffect(2.0)
Spacer()
}
Form { // Gathering data
Section {
TextField("Enter task name",
text: $taskName)
TextField("Enter due date",
text: $dueDate)
TextField("Enter subject",
text: $subject)
}
Section(header: Text("Enter other task details:")) {
TextField("Enter task weighting",
text: $weighting)
TextField("Enter total marks",
text: $totalMarks)
}
}
if buttonClicked == true {
Text("Task Created")
.font(.subheadline)
.foregroundColor(.green)
}
Button(
action: {
data.append(Task(taskName: self.taskName,
dueDate: self.dueDate,
subject: self.subject,
weighting: self.weighting,
totalMarks: self.totalMarks))
buttonClicked = true
},
label: {
Text("Create New Task")
.frame(width: 250,
height: 50,
alignment: .center)
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(8)
})
.padding()
}
}
}
}
struct AddAssignment_Previews: PreviewProvider {
static var previews: some View {
AddAssignment()
.preferredColorScheme(.light)
}
}
Task.swift(逻辑)
import SwiftUI
struct Task: Identifiable {
var id: String = UUID().uuidString
var taskName: String
var dueDate: String
var subject: String
var weighting: String
var totalMarks: String
}
var data: [Task] = [
Task(taskName: "Sample Task", dueDate: "1 Jan", subject: "Subject", weighting: "100", totalMarks: "100"),
Task(taskName: "Sample Task 2", dueDate: "2 Jan", subject: "Subject B", weighting: "100", totalMarks: "100"),
Task(taskName: "Sample Task 3", dueDate: "3 Jan", subject: "Subject C", weighting: "100", totalMarks: "100"),
]
ViewAssignment.swift (我的错误发生的地方:)
import SwiftUI
struct ViewAssignment: View {
var body: some View {
NavigationView {
List(data) { task in
NavigationLink (
destination: TaskDetailView(),
label: {
Image(systemName: "doc.append.fill")
.scaleEffect(2.5)
.padding()
VStack(alignment: .leading, spacing: 3) {
Text(task.taskName)
.fontWeight(.semibold)
.lineLimit(2)
Text(task.dueDate)
.font(.subheadline)
.foregroundColor(.secondary)
}
})
}
.navigationTitle("My Tasks")
}
}
}
struct ViewAssignment_Previews: PreviewProvider {
static var previews: some View {
ViewAssignment()
}
}