The code below presents a number of 'event' items in a from. Each item can be deleted or clicked on to navugate to a different view:
private func addDetails() -> some View {
Form {
Section(header: Text("Events").font(.headline)) {
ForEach(eventArray, id: \.self) { event in
NavigationLink(destination: EventDetailView(event: event)) {
HTextPair(labelText: event.wrappedType,
valueText: event.formattedDate)
}
}.onDelete(perform: deleteEvent)
}
}
I would like to prevent deletion of events unless the user has clicked on a custom 'Edit/Done' button on the navigation bar which simply toggles a boolean flag isEditing
. I believe that the following code should work:
private func addDetails() -> some View {
Form {
Section(header: Text("Events").font(.headline)) {
if isEditing {
ForEach(eventArray, id: \.self) { event in
NavigationLink(destination: EventDetailView(event: event)) {
HTextPair(labelText: event.wrappedType,
valueText: event.formattedDate)
}
}.onDelete(perform: deleteEvent)
} else {
ForEach(eventArray, id: \.self) { event in
NavigationLink(destination: EventDetailView(event: event)) {
HTextPair(labelText: event.wrappedType,
valueText: event.formattedDate)
}
}
}
}
}
}
With this revised version the everythin works as expected when isEditing == false
. When isEditing == true
navigation no longer works and only the last item becomes deletable.
I have also tried placing the items inside a List but that does not render correctly - the List takes up a single line. Is there a better way to conditionally enable/disable delete for each item?