Declaration
compose().scrollTargetBehavior(
behavior: SwiftUI.ScrollTargetBehavior
)nonisolated func scrollTargetBehavior(
_ behavior: some ScrollTargetBehavior
) -> some ViewParameters
behavior*SwiftUI.ScrollTargetBehavior
Discussion
A scrollable view calculates where scroll gestures should end using its
deceleration rate and the state of its scroll gesture by default. A
scroll behavior allows for customizing this logic. You can provide
your own ScrollTargetBehavior or use one of the built in behaviors
provided by SwiftUI.
Paging Behavior
SwiftUI offers a PagingScrollTargetBehavior behavior which uses the
geometry of the scroll view to decide where to allow scrolls to end.
In the following example, every view in the lazy stack is flexible in both directions and the scroll view will settle to container aligned boundaries.
ScrollView {
LazyVStack(spacing: 0.0) {
ForEach(items) { item in
FullScreenItem(item)
}
}
}
.scrollTargetBehavior(.paging)View Aligned Behavior
SwiftUI offers a ViewAlignedScrollTargetBehavior scroll behavior
that will always settle on the geometry of individual views.
ScrollView(.horizontal) {
LazyHStack(spacing: 10.0) {
ForEach(items) { item in
ItemView(item)
}
}
.scrollTargetLayout()
}
.scrollTargetBehavior(.viewAligned)
.safeAreaPadding(.horizontal, 20.0)You configure which views should be used for settling using the
View.scrollTargetLayout(isEnabled:) modifier. Apply this modifier to
a layout container like LazyVStack or HStack and each individual
view in that layout will be considered for alignment.
See also
More in Layout.
- alignmentGuideSets the view's vertical alignment.
- aspectRatioConstrains this view's dimensions to the specified aspect ratio.
- containerCornerOffsetAdjusts the view's layout to avoid the container view's corner insets for the specified edges.
- containerRelativeFramePositions this view within an invisible frame with a size relative to the nearest container.
- controlSizeSets the size for controls within this view.
- defaultScrollAnchorAssociates an anchor to control which part of the scroll view's content should be rendered by default.
- dynamicTypeSizeSets the Dynamic Type size within the view to the given value.
- fixedSizeFixes this view at its ideal size.
- flipsForRightToLeftLayoutDirectionSets whether this view mirrors its contents horizontally when the layout direction is right-to-left.
- framePositions this view within an invisible frame.
- geometryGroupIsolates the geometry (e.g. position and size) of the view from its parent view.
- gridCellAnchorSpecifies a custom alignment anchor for a view that acts as a grid cell.