Select Multiple Items in SwiftUI List
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| 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") } } } } }
|