Created
February 20, 2021 19:57
-
-
Save aerickson14/64fe21dea66535fae70bb951491df6e4 to your computer and use it in GitHub Desktop.
Multi select using onSelect callback
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 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