Skip to content

Instantly share code, notes, and snippets.

@aerickson14
Created February 20, 2021 19:57
Show Gist options
  • Save aerickson14/64fe21dea66535fae70bb951491df6e4 to your computer and use it in GitHub Desktop.
Save aerickson14/64fe21dea66535fae70bb951491df6e4 to your computer and use it in GitHub Desktop.
Multi select using onSelect callback
struct SelectHabitsView: View {
@State private var selectedHabits: Set<String> = []
let habits = ["H1", "H2", "H3"]
var body: some View {
List {
ForEach(habits, id: \.self) { habit in
HabitView(
habitatName: habit,
onSelect: { toggleSelection(for: habit) },
isSelected: isSelected(habit)
)
}
}
}
func toggleSelection(for habit: String) {
if selectedHabits.contains(habit) {
selectedHabits.remove(habit)
} else {
selectedHabits.insert(habit)
}
}
func isSelected(_ habit: String) -> Bool {
selectedHabits.contains(habit)
}
}
struct HabitView: View {
var habitatName: String
var onSelect: () -> Void
var isSelected: Bool
var body: some View {
HStack {
Text(habitatName)
Spacer()
}
.onTapGesture {
self.onSelect()
}
.background(isSelected ? Color.blue : Color.clear)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment