onScrollTargetVisibilityChange

Adds an action to be called with information about what views would be considered visible.

View ModifieriOS 18.0+macOS 15.0+tvOS 18.0+watchOS 11.0+visionOS 2.0+onScrollTargetVisibilityChange(idType:threshold:_:) in SwiftUI

Declaration

React
compose().onScrollTargetVisibilityChange<ID>({
  threshold?: number,
  action: (arg0: ID[]) => void,
})
Swift
nonisolated func onScrollTargetVisibilityChange<ID>(
    idType: ID.Type,
    threshold: Double = 0.5,
    _ action: @escaping ([ID]) -> Void
) -> some View
where ID : Hashable

Parameters

  • options.thresholdnumber

    The amount required to be visible within the viewport of the the scrollview before the action is fired. By default when the view has crossed more than 50% on-screen, the action will be called.

  • options.action*(arg0: ID[]) => void

    The action which will be called when the views within the scroll view cross the provided threshold. The callback will include which views are considered visible.

Discussion

Use this modifier along with the modifier View.scrollTargetLayout(isEnabled:) to be informed when the views in the targetted scroll view have crossed the provided threshold to be considered on/off screen.

ScrollView {
    LazyVStack {
        ForEach(models) { model in
            CardView(model: model)
        }
    }
    .scrollTargetLayout()
}
.onScrollTargetVisibilityChange(for: Model.ID.self, threshold: 0.2) { onScreenCards in
    // Disable video playback for cards that are offscreen...
}

See also

More in Events and lifecycle.