swiftswiftuiswiftui-listswiftui-scrollview

How does scrollIndicatorsFlash(trigger value: some Equatable) not require a binding to observe changes?


I'm learning about Lists and ScrollViews in SwiftUI and one of the modifiers that is available is:

public func scrollIndicatorsFlash(trigger value: some Equatable) -> some View

Documentation

My question is, when I use this, I pass a Bool value, not a Binding<Bool>. How do the scroll views and lists observe that this value has changed if I'm only passing the raw value?

The Bool that I'm passing is a @State variable defined as such: @State var flashIndicators = false. This is very similar to the example that is in the documentation for that method.


Solution

  • How do the scroll views and lists observe that this value has changed if I'm only passing the raw value?

    It all starts by SwiftUI calling your view's body. body returns a view model representing the view you want to create. At the same time, SwiftUI constructs a dependency graph, recording what @States and @Bindings (and other such proeprty wrappers) your view depends on.

    When you say .scrollIndicatorsFlash(trigger: flashIndicators), the getter of flashIndicators gets called, and in turn the getter of State.wrappedValue gets called. This is how SwiftUI know that your view depends on the @State flashIndicators.

    Therefore, when those dependencies is set, SwiftUI can call your view's body again, and compare the result with the old view model, and determine what changed. Suppose you set flashIndicators from false to true. SwiftUI knows that body returned a view model with .scrollIndicatorsFlash(trigger: false) last time, and when it called body for the second time (because a dependency has changed), body now returns a view model with .scrollIndicatorsFlash(trigger: true).

    SwiftUI does this comparison not only for scrollIndicatorsFlash, but also for many other modifiers. This is how onChange detects a change. This is how animation(_:value:) knows when to animate. This is how things like opacity(_:) knows when to change the opacity, and so on.


    scrollIndicatorsFlash doesn't need to take a Binding, because SwiftUI doesn't need to change the value you passed in. SwiftUI doesn't care one bit about the value of the trigger: parameter. All it cares is when the value changes.

    Other modifiers like sheet(isPresented:) takes a Binding<Bool> because SwiftUI is designed to set isPresented back to false when the user dismisses the sheet.