How it works
ScrollAnchorRole describes which aspect of a scroll view's behavior a content anchor governs. A scroll view can have more than one notion of an anchor at the same time — the point it scrolls to by default and the point it keeps pinned when content grows or shrinks — and this type lets you name which of those you mean. You reach for ScrollAnchorRole when you pass an anchor to a modifier like defaultScrollAnchor(_:for:), using the role to disambiguate whether your UnitPoint should drive initial alignment or size-change stabilization.
Choose a role to qualify an anchor
ScrollAnchorRole is a small set of constants, each identifying one job an anchor can perform. Rather than constructing a value directly, you select the appropriate case at the call site where an anchor is needed, as with
.alignmentin.defaultScrollAnchor(.bottom, for: .alignment).Pass the role through the for: parameter
Anchor modifiers accept a ScrollAnchorRole through their
for:argument, binding the supplied UnitPoint to that specific behavior. In the example,for: .alignmenttells the scroll view that the.bottomanchor controls where content is positioned initially, so the list opens scrolled to its last message.Use .alignment to set the resting position
The
.alignmentrole makes the anchor decide how content lines up within the scroll view's visible region when there is no explicit scroll offset. Combined here with.bottom, it anchors theForEachofText("Message \(i)")rows to the bottom edge on first appearance.Use .sizeChanges to hold a point steady
The companion
.sizeChangesrole keeps a chosen anchor point fixed as the content's size changes, so newly inserted or removed items don't visually shift what the reader is looking at. Swapping the role on the same.defaultScrollAnchorcall repurposes the.bottomanchor from initial placement to growth stabilization.Apply it once on the scroll view
Because ScrollAnchorRole is consumed by a modifier on the scroll view itself, you attach it where the
ScrollViewis declared rather than on individual rows. The single.defaultScrollAnchor(.bottom, for: .alignment)here configures anchoring for the entire scrolling region.
for: .alignment to for: .sizeChanges in .defaultScrollAnchor(.bottom, for: .alignment) to see the anchor pin the bottom of the list as content grows instead of merely choosing the opening position.Example & preview
Press Run live & edit to compile it in your browser — then edit the Swift on the left and the preview re-renders live.
struct ScrollAnchorRoleDemo: View {
var body: some View {
ScrollView {
VStack(spacing: 12) {
ForEach(1..<21) { i in
Text("Message \(i)")
.frame(maxWidth: .infinity)
.padding()
.background(.blue.opacity(0.15))
.cornerRadius(8)
}
}
.padding()
}
.defaultScrollAnchor(.bottom, for: .alignment)
}
}