Select Multiple Items in SwiftUI List
The only way to get multiple selection in SwiftUI right now is by using EditButton
. However, that's not the only instance you might want to use multiple selection, and it would probably confuse users if you used EditButton
multiple selection when you're not actually trying to edit anything.
I assume what you're really looking for is something like this:
Below is the code I wrote to create this:
struct MultipleSelectionList: View {
@State var items: [String] = ["Apples", "Oranges", "Bananas", "Pears", "Mangos", "Grapefruit"]
@State var selections: [String] = []
var body: some View {
List {
ForEach(self.items, id: \.self) { item in
MultipleSelectionRow(title: item, isSelected: self.selections.contains(item)) {
if self.selections.contains(item) {
self.selections.removeAll(where: { $0 == item })
}
else {
self.selections.append(item)
}
}
}
}
}
}
struct MultipleSelectionRow: View {
var title: String
var isSelected: Bool
var action: () -> Void
var body: some View {
Button(action: self.action) {
HStack {
Text(self.title)
if self.isSelected {
Spacer()
Image(systemName: "checkmark")
}
}
}
}
}
First add this to your view
@State var selectedItems = Set<UUID>()
The type of the Set
depends on the type you use to id:
the items in the ForEach
Next declare the List
List(selection: $selectedItems) {
ForEach(items, id: \.id) { item in
Text("\(item.name)")
}
}
Now whatever you select gets added to the selectedItems Set
remember to clear it out after you use it.