skip to content

In a SwiftUI feed that inserts newer posts at the top, how do you keep the reader's place using scrollPosition?

level: seniorimportance: should knowfreq 42%

answer

  1. the binding tracks a view identity
  2. targets come from one marked layout
  3. an edge position versus an id position
  4. iOS 17 binding, iOS 18 type

basics

~20 s

Bind the ScrollView's position to a post id with scrollPosition(id:) on iOS 17 or a ScrollPosition on iOS 18, and mark the LazyVStack with scrollTargetLayout(). SwiftUI then tracks the top post and tries to keep it in view as data changes.

solid answer

~40 s

`scrollPosition(id:anchor:)` (iOS 17) binds an optional id. With `scrollTargetLayout()` on the `LazyVStack`, SwiftUI writes the id of the top-most visible post into it as the reader scrolls, and writing an id scrolls to that post. Apple documents that SwiftUI will attempt to keep the view whose identity is in the binding visible when the system would otherwise scroll it away, for example when the backing data is reordered or the scroll view resizes; that attempt is what holds the reader's place when newer posts arrive above. iOS 18's `ScrollPosition` type does the same and can also target an edge or an offset: a 'new posts' button calls `position.scrollTo(edge: .top)`. Keep ids stable, because a regenerated id cannot be found. For bottom-anchored content, `defaultScrollAnchor(.bottom)` sets the starting point and guides size changes.

code

swift · 35 lines
swift
import SwiftUI

struct Post: Identifiable, Sendable {
    let id: Int
    let text: String
}

struct HomeTimeline: View {
    let posts: [Post]          // newest first; new posts are inserted at index 0
    @Binding var unseenCount: Int
    @State private var position = ScrollPosition(idType: Post.ID.self)

    var body: some View {
        ScrollView {
            LazyVStack(alignment: .leading) {
                ForEach(posts) { post in
                    Text(post.text)
                }
            }
            .scrollTargetLayout()
        }
        .scrollPosition($position)
        .overlay(alignment: .top) {
            if unseenCount > 0 {
                Button("\(unseenCount) new posts") {
                    withAnimation { position.scrollTo(edge: .top) }
                    unseenCount = 0
                }
                .buttonStyle(.borderedProminent)
            }
        }
    }

    var topVisiblePostID: Post.ID? { position.viewID(type: Post.ID.self) }
}

go deeper

for a junior

Recall that scrollPosition binds the id of the post at the top, and that the stack holding the posts needs scrollTargetLayout().

for a middle

Explain how the binding is read and written, what the anchor changes, and which pieces need iOS 17 versus iOS 18.

for a senior

Diagnose a timeline that jumps on refresh: missing target layout, regenerated ids, a binding reset on every load, or a point position.

for a principal

Agree the product behaviour for new content, staying in place or jumping to the top, and encode it once in a shared feed container.

## The problem A home timeline shows newest posts first. While the reader is several posts down, a refresh inserts five newer posts at index 0. Without a position to protect, nothing tells SwiftUI which post the reader cares about, so the inserted rows can shift the content they were reading. The fix is to give the scroll view a **semantic position**: an identity, not an offset. ## The APIs and their releases | API | Since | What it binds | |---|---|---| | `scrollPosition(id:anchor:)` | iOS 17 | An optional id of the top-most (or anchor-chosen) target view | | `ScrollPosition` + `scrollPosition(_:anchor:)` | iOS 18 | A value that holds an id, an edge or a point | | `defaultScrollAnchor(_:)` | iOS 17 | Where content starts and how size changes are handled | | `defaultScrollAnchor(_:for:)` | iOS 18 | The same, per role: `initialOffset`, `sizeChanges`, `alignment` | All of them work with a `ScrollView`; the id-based ones need **`scrollTargetLayout()`** on the layout whose children are the targets, usually the `LazyVStack` around the `ForEach`. ## How an id-based position behaves 1. As the reader scrolls, SwiftUI writes the **top-most visible target's id** into the binding. With an anchor such as `.bottom`, it prefers the bottom-most view instead. 2. Writing a new id **scrolls to that view**. With no anchor, SwiftUI scrolls the minimal amount; with an anchor, it aligns the view to it. 3. SwiftUI **attempts to keep the bound view visible** when events would otherwise scroll it away. Apple's examples include reordered data, a resized scroll view, such as a rotation, and an initial layout whose binding names a view other than the first. Apple's wording is "attempt": treat it as the framework's intent and verify the insert-above case on the releases you support. ## ScrollPosition on iOS 18 `ScrollPosition` is a value you keep in `@State`, created with `ScrollPosition(idType: Post.ID.self)`. It adds: - `scrollTo(id:anchor:)`, `scrollTo(edge:)`, `scrollTo(point:)`, and `scrollTo(x:)` and `scrollTo(y:)` for offsets; - `viewID(type:)` to read the current id with its type; - documented stability rules: an **edge** position keeps a top-aligned scroll view at the top when content size changes; a **point** position is not kept when content size changes. That last rule matters for feeds. If the position is the top edge, new posts appear and the reader stays at the very top, which suits the moment after the reader publishes a post. If the position is an id, the reader stays with the post they were reading, and a "5 new posts" button calls `position.scrollTo(edge: .top)` when they choose. ## Pitfalls - **No `scrollTargetLayout()`**: the binding never updates, because no views are scroll targets. - **Unstable ids**: a refresh that recreates posts with fresh UUIDs leaves the bound id pointing at nothing. - **Type mismatch**: the binding's wrapped type must match the `ForEach` element's id type. - **Writing the binding on every refresh**: resetting it to the first post's id undoes the preservation you wanted. - **Mixing up `defaultScrollAnchor`**: it sets the initial position and guides size changes; it does not track a post. `.bottom` suits content whose newest entries are at the end. ## A review checklist for scroll stability 1. Is the `ForEach` inside a layout marked with `scrollTargetLayout()`? 2. Are post ids stable across refreshes, coming from the server rather than generated on decode? 3. Is the position bound by id while the reader browses, and switched to the top edge only on an explicit action? 4. Does any code write the binding on each refresh, undoing the preservation? 5. Has the insert-above case been tried on the oldest supported release, since the documentation promises an attempt rather than a guarantee? ## Chat-like and timeline-like content - Newest at the top, as in a home timeline: id-based position plus an explicit jump to the top edge. - Newest at the bottom, as in a conversation log: `defaultScrollAnchor(.bottom)` to start at the end, and on iOS 18 `defaultScrollAnchor(_:for:)` to keep a different alignment for short content.

  • How do you read which post is on screen with the iOS 18 ScrollPosition type?
    Call position.viewID(type: Post.ID.self), which returns the current view id as an optional of that type. SwiftUI fills it from the views in the scroll view's scroll target layout as the reader scrolls, so the stack must carry scrollTargetLayout(), the same requirement as the iOS 17 binding.
  • What is the difference between an edge position and a point position when content grows?
    Apple documents that an edge position is kept stable, so a top-aligned scroll view stays at the top as content size changes. A point position is not: SwiftUI will not try to keep that exact offset, nor update it, when the content size changes.

  • scrollPosition(id:) updates as the user scrolls even without scrollTargetLayout().
  • defaultScrollAnchor(.top) keeps the reader on the same post when data changes.
  • A point-based ScrollPosition keeps the same content in view as rows are inserted.
  • ScrollPosition is available on iOS 17 alongside scrollPosition(id:).
  • Regenerating post ids on refresh does not affect the bound position.

scrollPosition(id:anchor:) and defaultScrollAnchor(_:) need iOS 17; the ScrollPosition type, scrollPosition(_:anchor:) and defaultScrollAnchor(_:for:) need iOS 18.