I'm add a row of tag buttons as a filter. Each button have two state, selected and unselected. It always reports error for dictionary binding. Please see bellow comments in code.
struct TagButton: View {
var body: some View {
Button(action: {
self.selected.toggle()
}) {
if selected {
Text(name)
.underline()
} else {
Text(name)
}
}
.padding()
}
@Binding var selected: Bool
let name: String
}
struct TagsView: View {
@Binding var tags: [String:Bool]
var body: some View {
ScrollView(.horizontal) {
HStack {
ForEach(tags.keys.sorted(), id: \.self) {k in // I don't need "sorted" here, but need a key array
TagButton(selected: self.$tags[k], name: k) // [k] error: Missing argument label 'dynamicMember:' in subscript
}
}
}
}
}
Thanks, Rob! The second method works. But I don't feel comfortable with it. From design perspective, selected of TagButton can not be optional. Further more, if I use view like Toggle, it does not accept optional Binding.
Ah, my fault. I overlooked the binding function. It's kind of magic to me. How is the Binding instance created by us working for subscriber/publisher? I assuming @State is the publisher and views that uses it via @Binding are subscribers. Would you help me understand how Binding and State are linked?