How to let users delete rows from a list
How to let users delete rows from a list 관련
Updated for Xcode 15
SwiftUI provides two ways to let us delete rows from a list: a simple way supported on iOS 16.0 or later, and a more advanced way that works on older iOS versions too. Regardless of which approach you choose, you can also selectively disable deletion for rows using the deleteDisabled()
modifier.
The simple approach to deletion works great if you just want users to swipe to delete items from an array, without adding any additional logic. To use it, use a data binding with your list and pass in the editActions
parameter, like this:
struct ContentView: View {
@State private var users = ["Glenn", "Malcolm", "Nicola", "Terri"]
var body: some View {
NavigationStack {
List($users, id: \.self, editActions: .delete) { $user in
Text(user)
}
}
}
}
That immediately lets users swipe to delete rows, and the users
array will be updated as they do so. If you want to let them move the items as well, use .all
rather than just .delete
.
If you want to disable deletion for one row, use deleteDisabled()
with whatever criteria you have. For example, we could say that the user can delete freely from the list as long as there's always at least 1 row remaining:
struct ContentView: View {
@State private var users = ["Glenn", "Malcolm", "Nicola", "Terri"]
var body: some View {
NavigationStack {
List($users, id: \.self, editActions: .delete) { $user in
Text(user)
.deleteDisabled(users.count < 2)
}
}
}
}
For the more complex approach to deletion, we can attach an onDelete(perform:)
modifier to a ForEach
inside a list, and have it call a method of our choosing when a delete operation happens. This handler needs to have a specific signature that accepts multiples indexes to delete, like this:
func delete(at offsets: IndexSet) {
// delete the objects here
}
Inside there you will usually want to call Swift's remove(atOffsets:)
method to delete the requested rows from your sequence. Because SwiftUI is watching your state, any changes you make will automatically be reflected in your UI.
For example, this code creates a ContentView
struct with a list of three items, then attaches an onDelete(perform:)
modifier that removes any item from the list:
struct ContentView: View {
@State private var users = ["Paul", "Taylor", "Adele"]
var body: some View {
NavigationStack {
List {
ForEach(users, id: \.self) { user in
Text(user)
}
.onDelete(perform: delete)
}
.navigationTitle("Users")
}
}
func delete(at offsets: IndexSet) {
users.remove(atOffsets: offsets)
}
}
If you run that code you'll find you can swipe to delete any row in the list.
Tips
In case you were wondering, onDelete()
exists as a modifier for ForEach
but not for List
directly. This is because lists can include static rows, which of course cannot be deleted.