Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating a @Binding value without triggering changes

Tags:

swift

swiftui

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?

like image 825
Duck Avatar asked Apr 30 '26 05:04

Duck


1 Answers

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))
    }

}
like image 147
Bradley Mackey Avatar answered May 02 '26 20:05

Bradley Mackey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!