Below is my code. I have a toolbar button for enabling EditMode, when EditMode is enabled, it won't show the rest of the task details, and just be a button saying "Edit taskName" This works for the most part, except when ran, all but the last list element will be updated, but the last one will still show all details. I can't begin to understand why. I understand if you need more code parts but this should be enough imo. Also I learned SwiftUI maybe 2 weeks ago, so any bad practice or tips you see are greatly appreciated.
import SwiftUI
struct ScheduleView: View {
private var schedule: [Task]
@State private var editMode = false
@State private var editReady = false
@State private var editTask: Task
init(schedule: [Task]) {
self.schedule = schedule
self.schedule.sort()
self.editTask = Task(taskString: "")
}
var body: some View {
List{
ForEach(schedule,id: \.self){ task in
HStack{
if editMode {
Image(systemName: "pencil")
Button("Edit \(task.getName())"){
editTask = task
editReady = true
}
} else{
Text(task.getName())
Text(task.getType())
Text(task.getDate(),format: .dateTime.day().month())
if task.getBool(){
Text(task.getTime(),format: .dateTime.hour().minute())
}
}
}
}
}
.sheet(isPresented: $editReady) {
EditView(editTask: editTask)
}
.toolbar(){
ToolbarItem(placement: .automatic){Button("Edit"){
editMode.toggle()
}}
}
}
}
Tried removing the Image, changing from List to Form, but not much else. Like it said this actually make no sense to me idk how this is happening.
Make Task conform to the Identifiable protocol and leave out the id:.self. The ForEach needs unique ids or it will get things mixed up, especially with moves and deletes but also apparently in your case. If you didn't want to change Task to Identifiable you could write: ForEach(schedule.indices,id: .self){ i in let task = schedule[i]