Hi folks,
I'm struggling to implement a custom view which can take Binding as an argument and implement two-way updates of that value.
So basically I'm implementing my custom slider and want its initializer to look like this:
MySlider(value: <binding)
___
What I'm struggling with:
1. How do I subscribe to remote updates of the binding value so that I can update the view's state?
2. Is there any nice way to bind a Binding with @State property?
___
Here's my current implementation so far which is not perfect.
struct MySlider: View {
@Binding var selection: Float?
@State private var selectedValue: Float?
init(selection: Binding) {
self._selection = selection
// https://stackoverflow.com/a/58137096
_selectedValue = State(wrappedValue: selection.wrappedValue)
}
var body: some View {
HStack(spacing: 3) {
ForEach(someValues) { (v) in
Item(value: v,
isSelected: v == self.selection)
.onTapGesture {
// No idea how to do that other way so I don't have to set it twice
self.selection = v
self.selectedValue = v
}
}
}
}
}