Here is the view in which it works
struct MileageHistoryView: View {
let vehicle: Vehicle
init(for vehicle: Vehicle) {
self.vehicle = vehicle
}
@Environment(\.modelContext) private var context
@Environment(\.editMode) private var editMode
var sorted: [Mileage] {
guard let history = vehicle.mileageHistory else { return [] }
return history.sorted(by: { $0.timestamp > $1.timestamp })
}
var body: some View {
List {
ForEach(sorted) { mileage in
MileageListItem(mileage, editing: Binding(get: {editMode?.wrappedValue.isEditing ?? false}, set: {_ in }))
}
.onDelete(perform: deleteMileage)
.deleteDisabled(editMode?.wrappedValue.isEditing ?? false ? false : true)
}
.id(editMode?.wrappedValue.isEditing)
.navigationTitle("Mileage History")
.scrollContentBackground(.hidden)
.toolbar {
ToolbarItem(placement: .topBarTrailing, content: {
EditButton()
})
}
}
}
Here is the other view where it doesn't work. In this view, it seems like when the EditButton is pressed, no change is happening with the editMode so deleteDisabled() is always set to true.
struct VehiclesView: View {
@Environment(\.modelContext) private var context
@Environment(\.editMode) private var editMode
// Local
@Query private var vehicles: [Vehicle]
@State private var addVehicle = false
@AppStorage("vehicle-edit-alert") private var showEditAlert = true
@State private var editAlert = false
@State private var editShown = false
var body: some View {
NavigationStack {
List {
ForEach(vehicles) { vehicle in
NavigationLink(destination: VehicleView(vehicle), label: {
VehicleListItem(vehicle)
})
}
.onDelete(perform: deleteVehicle)
.deleteDisabled(self.editMode?.wrappedValue.isEditing ?? false ? false : true)
}
.id(self.editMode?.wrappedValue.isEditing)
.scrollContentBackground(.hidden)
.navigationTitle("Vehicles")
.toolbar {
ToolbarItem(placement: .topBarLeading, content: {
if showEditAlert && !editShown {
Button("Edit") { editAlert = true }
} else {
EditButton()
}
})
ToolbarItem(placement: .topBarTrailing, content: {
Button(action: { addVehicle.toggle() }, label: { Image(systemName: "plus") })
.accessibilityHint("Opens the view to add a Vehicle")
})
}
.fullScreenCover(isPresented: $addVehicle, content: {
VehicleEditor()
})
}
.scrollIndicators(.hidden)
}
}
When EditButton() is used in the second view the list item is grayed out, but the buttons to delete aren't there.
Does anybody know why this is happening?