< How to add sections to a list | How to set the background color of list rows using listRowBackground() > |
Updated for Xcode 14.2
If you have configured a SwiftUI list view to support deletion or editing of its items, you can allow the user to toggle editing mode for your list view by adding an EditButton
somewhere.
For example, this ContentView
struct defines an array of users, attaches an onDelete()
method, then adds an edit button to the navigation bar:
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)
}
.toolbar {
EditButton()
}
}
}
func delete(at offsets: IndexSet) {
users.remove(atOffsets: offsets)
}
}
Download this as an Xcode project
When that is run, you’ll find you can tap the edit button to enable or disable editing mode for the items in the list.
SAVE 50% To celebrate WWDC23, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.
Link copied to your pasteboard.