Contents

scrollTargetAnchor

The preferred alignment of the view within a scroll view’s visible region when scrolling to a view.

Declaration

var scrollTargetAnchor: UnitPoint? { get set }

Discussion

Use this API in conjunction with a ScrollViewProxy/scrollTo(_:anchor) or when updating the binding provided to a scrollPosition(id:anchor:).

@Binding var position: Item.ID?

var body: some View {
    ScrollView {
        LazyVStack {
            ForEach(items) { item in
                ItemView(item)
            }
        }
        .scrollTargetLayout()
    }
    .scrollPosition(id: $position)
    .safeAreaInset(edge: .bottom) {
        Button("Scroll To Bottom") {
            withAnimation {
                withTransaction(\.scrollTargetAnchor, .bottom) {
                    position = items.last?.id
                }
            }
        }
    }
}

When used with the scrollPosition(id:anchor:) modifier, this value will be preferred over the anchor specified in the modifier for the current transaction.

See Also

Getting information about a transaction