I have a struct which's init is like that
@Binding var fieldValue:Float
init(fieldValue:Binding<Float>) {
self._fieldValue = fieldValue
}
at some point I would like to update fieldValue without triggering updates on other points listening to $fieldValue.
Is that possible?
The problem is that SwiftUI synchronizes all Bindings by default and there's no way to explicitly disable this behaviour.
However, we can work around it by wrapping the property in an ObservableObject and get a custom Binding based on the behaviour that is desired, using the Binding(get:set:) initializer.
(Note that this may not work well with the standard UI components, like Slider, as they may expect a Binding update in order to work correctly.)
class ValueContainer: ObservableObject {
private var fieldValue: Float = 0
func getBinding(isTriggering: Bool) -> Binding<Float> {
Binding { [self] in
self.fieldValue
} set: { [self] newValue in
self.fieldValue = newValue
if isTriggering {
self.objectWillChange.send()
}
}
}
}
struct DoesNotTriggerUpdate: View {
@ObservedObject var container: ValueContainer
var body: some View {
Slider(value: container.getBinding(isTriggering: false))
}
}
struct DoesTriggerUpdate: View {
@ObservedObject var container: ValueContainer
var body: some View {
Slider(value: container.getBinding(isTriggering: true))
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With