Skip to content

Instantly share code, notes, and snippets.

@dippnerd
Created February 8, 2021 18:55
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dippnerd/5841898c2cf945994ba85871446329fa to your computer and use it in GitHub Desktop.
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)
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())
}
}
@JoshHrach
Copy link

Because you aren't mutating the sourceItems array, it doesn't need to have the @State annotation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment