Created
February 8, 2021 18:55
-
-
Save dippnerd/5841898c2cf945994ba85871446329fa to your computer and use it in GitHub Desktop.
One way to create a SwiftUI form list of items that lets you select more than one (unlike the stock picker form)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct MultiSelectPickerView: View { | |
//the list of all items to read from | |
@State var sourceItems: [String] | |
//a binding to the values we want to track | |
@Binding var selectedItems: [String] | |
var body: some View { | |
Form { | |
List { | |
ForEach(sourceItems, id: \.self) { item in | |
Button(action: { | |
withAnimation { | |
if self.selectedItems.contains(item) { | |
//you may need to adapt this piece, my object has an ID I match against rather than just the string | |
self.selectedItems.removeAll(where: { $0 == item }) | |
} else { | |
self.selectedItems.append(item) | |
} | |
} | |
}) { | |
HStack { | |
Image(systemName: "checkmark") | |
.opacity(self.selectedItems.contains(item) ? 1.0 : 0.0) | |
Text("\(item)") | |
} | |
} | |
.foregroundColor(.primary) | |
} | |
} | |
} | |
.listStyle(GroupedListStyle()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Because you aren't mutating the
sourceItems
array, it doesn't need to have the@State
annotation.