Is there a way to remove or deactivate swipe to delete functionality that remove items only per edit button?
Asked
Active
Viewed 754 times
0
-
@Yrb You should take a closer look at the question. – Intronaen Jan 15 '21 at 23:55
-
Yep, you are right. . . I COMPLETELY misread that one. That's what I get for doing this at the end of the day... – Yrb Jan 15 '21 at 23:58
-
If my answer from last week helped, you can accept the answer so it easier for people to find this question in the future. (also you get some bonus reputation) – George Jan 22 '21 at 00:07
1 Answers
3
You can limit the delete functionality of a List
/Form
depending on the EditMode
state, by using deleteDisabled(_:)
.
The following is a short example demonstrating deleting which only works in edit mode:
struct ContentView: View {
@State private var data = Array(1 ... 10)
var body: some View {
NavigationView {
Form {
DataRows(data: $data)
}
.navigationTitle("Delete Test")
.toolbar {
EditButton()
}
}
}
}
struct DataRows: View {
@Environment(\.editMode) private var editMode
@Binding private var data: [Int]
init(data: Binding<[Int]>) {
_data = data
}
var body: some View {
ForEach(data, id: \.self) { item in
Text("Item: \(item)")
}
.onMove { indices, newOffset in
data.move(fromOffsets: indices, toOffset: newOffset)
}
.onDelete { indexSet in
data.remove(atOffsets: indexSet)
}
.deleteDisabled(editMode?.wrappedValue != .active)
}
}

George
- 25,988
- 10
- 79
- 133
-
2Hm, looks like this does not work for iOS 16 anymore, at least for the Beta. All elements stay undeletable, even in edit mode. – Thomas Jul 31 '22 at 11:03
-
@Thomas Are you sure you have the `onDelete` modifier added? If this exact code in entirety doesn’t work, then yeah - likely a bug. – George Jul 31 '22 at 11:06
-
Yes, just checked again. @George Don't know if it's a bug or will not work in iOS 16 anymore.... – Thomas Aug 02 '22 at 11:14
-
@Thomas You're right - very likely a bug somewhere with the updating of the `deleteDisabled` modifier, because the `editMode` is still updating appropriately – George Aug 02 '22 at 20:58
-
This bug is very strange. I have made a custom edit button for testing purposes. It toggles a bool binding `cellsDeletable` and after a few seconds also changes the environment editMode to `.active`. The form rows / cells observe the state of the cellsDeletable value via `.deleteDisabled(!cellsDeletable)`. During the time where the cellsDeletable is set to True and editMode hasn't yet been set to .active the cells can be deleted by a swipe. However as soon as the editMode is changed, the cells can't be deleted anymore. – David Mar 08 '23 at 21:12
-
Somehow I found a [workaround](https://stackoverflow.com/questions/73704545/swiftui-deletedisabled-is-not-working-as-expected/75678446#75678446) – David Mar 08 '23 at 21:35