skip to content

In SwiftUI, how do you jump a scrolling feed to a specific post with ScrollViewReader and ScrollViewProxy.scrollTo(_:anchor:)?

level: middleimportance: should knowfreq 55%

answer

  1. a reader wraps the scroll view
  2. the proxy arrives in a closure
  3. ids must match the row identity
  4. call it from an action, not body

basics

~20 s

Wrap the ScrollView in a ScrollViewReader, then call the proxy's scrollTo(_:anchor:) with the target row's id from an action such as a button or onChange. The id must equal the row's identity, and an anchor like .top sets the alignment.

solid answer

~40 s

`ScrollViewReader` (iOS 14) hands its content closure a `ScrollViewProxy`. Rows in a `ForEach` over `Identifiable` posts already carry their ids, and other views can get one with `.id(_:)`. To jump, call `proxy.scrollTo(post.id, anchor: .top)` from an action, such as a button, a gesture or `onChange(of:)` reacting to a deep link; Apple warns that calling the proxy while the content closure is building views is a runtime error. Wrap the call in `withAnimation` to animate it. An anchor such as `.top` sets where the target lands; the default, `nil`, requests no alignment and just brings the post into view. The value must equal a row's id, including its type: passing an `Int` index to rows identified by `UUID` compiles and silently does nothing. On iOS 17 and later, `scrollPosition(id:)` offers a binding-based alternative.

code

swift · 35 lines
swift
import SwiftUI

struct Post: Identifiable {
    let id: UUID
    let text: String
}

struct FeedView: View {
    let posts: [Post]
    @Binding var linkedPostID: Post.ID?

    var body: some View {
        ScrollViewReader { proxy in
            ScrollView {
                LazyVStack(alignment: .leading) {
                    ForEach(posts) { post in
                        Text(post.text)
                    }
                }
            }
            .onChange(of: linkedPostID) { _, id in
                guard let id else { return }
                withAnimation {
                    proxy.scrollTo(id, anchor: .top)
                }
            }
            .toolbar {
                Button("Top") {
                    guard let first = posts.first else { return }
                    withAnimation { proxy.scrollTo(first.id, anchor: .top) }
                }
            }
        }
    }
}

go deeper

for a junior

Recall the shape: ScrollViewReader around the ScrollView, rows with ids, and proxy.scrollTo(id, anchor:) inside a button action.

for a middle

Explain anchors, why the id value and type must match the row identity, and why the proxy can only be used from actions.

for a senior

Debug a jump that silently does nothing, such as unstable or mismatched ids, and know when scrollPosition(id:) replaces the reader on iOS 17.

for a principal

Choose one programmatic scrolling approach per deployment target so deep links and restoration behave the same across the app's feeds.

## The pieces **`ScrollViewReader`** is a view, available since iOS 14, that provides **programmatic scrolling** for the scroll views inside it. Its content closure receives a **`ScrollViewProxy`**, and the proxy has one method: **`scrollTo(_:anchor:)`**. Its declaration is generic over any `Hashable` id, with `anchor: UnitPoint? = nil`. You never create a proxy yourself. It exists only inside the reader's closure, and you capture it in the actions you declare there. ## Steps to jump to a post 1. **Wrap** the `ScrollView` (or several) in `ScrollViewReader { proxy in ... }`. 2. **Give targets an identity.** Rows produced by `ForEach(posts)` over `Identifiable` values are identified by `post.id`. A view outside a `ForEach`, such as a header, gets one with `.id(_:)`. 3. **Call from an action.** A button, a gesture handler, `onChange(of:initial:_:)` reacting to a selected id, or a `task` all work. 4. **Choose an anchor.** `.top` puts the post's top at the top of the viewport; `.center` centres it; the default, `nil`, requests no alignment and simply brings the post into view (Apple's scroll-position pages describe a nil anchor as scrolling the minimal amount). 5. **Animate if wanted** by wrapping the call in `withAnimation`. ## What goes wrong | Mistake | What happens | Fix | |---|---|---| | Calling `proxy.scrollTo` while the reader's content is being built | Apple documents a runtime error | Call it only from actions such as handlers or `onChange` | | Passing an index (`Int`) to rows identified by `UUID` | Compiles, matches no row, nothing moves | Pass the same id value and type the rows use | | Ids regenerated on every refresh | The id you saved no longer exists | Keep ids stable in the model | | Expecting to read the current position from the proxy | The proxy only scrolls; it does not report | Use `scrollPosition(id:)` on iOS 17 or later | | Using the one-parameter `onChange(of:perform:)` | Deprecated since iOS 17 | Use `onChange(of:initial:_:)` with old and new values | The type mismatch deserves attention because the compiler cannot help: `scrollTo` accepts any `Hashable`, so `proxy.scrollTo(3)` type-checks happily against rows whose ids are `UUID`s, and at runtime no row matches. Apple's own `ScrollViewProxy` page still shows `onChange(of:perform:)`; that one-parameter form was deprecated in iOS 17, so new code uses the two-value closure. ## Typical uses in a feed - **"Back to top"** in a toolbar: scroll to the first post's id with anchor `.top`. - **Deep link to a post**: when a notification sets a selected id, `onChange` scrolls to it. - **Restore after navigation**: save the id the reader was on and scroll back to it when the screen returns. - **Jump between sections**: give each day header an id and scroll to it from an index strip. ## Scope and structure - **Wrap narrowly.** The reader only needs to enclose the scroll view and the controls that call the proxy; wrapping a whole screen makes the closure large for no gain. - **One reader, several scroll views.** Apple notes that a reader can wrap one or more scroll views, and the proxy serves the scroll views inside that hierarchy; a jump targets the view whose id matches. - **Distinct id spaces.** If day headers and posts are both targets, give them ids that cannot be confused, for example separate wrapper types, so a jump to a day never lands on a post. - **Ids from the model.** Keep the id you scroll to in state or in the model, such as the id a notification carried, never a value computed from the current row positions. ## ScrollViewReader beside the newer APIs | API | Since | Reads the position? | Scrolls programmatically? | |---|---|---|---| | `ScrollViewReader` + `scrollTo(_:anchor:)` | iOS 14 | No | Yes, to an id | | `scrollPosition(id:anchor:)` | iOS 17 | Yes, top-most target id | Yes, by writing the binding | | `ScrollPosition` with `scrollPosition(_:anchor:)` | iOS 18 | Yes | Yes, to an id, an edge or an offset | The reader remains the most portable choice and works with any identified view, while the binding-based APIs need `scrollTargetLayout()` on the container whose children are the targets. Keeping the reader small also helps: wrap only the scroll view and the controls that need the proxy, not the whole screen.

  • What does the anchor argument change if you omit it?
    The default is nil, which requests no alignment: SwiftUI only brings the target into view, which Apple's scroll-position pages describe as scrolling the minimal amount. Passing .top, .center or .bottom instead aligns that point of the target with the same point of the visible region, which is what a back-to-top button or a deep link usually wants.
  • How would you jump to a day header rather than a post?
    Give the header view an explicit identity with .id(day.id), using a type distinct from post ids, and call proxy.scrollTo(day.id, anchor: .top) from the index control's action. Any identified view inside the scroll view can be a target, not only ForEach rows.

  • You can call proxy.scrollTo directly while the reader builds its content.
  • Passing a row's array index works because SwiftUI maps it to the id.
  • ScrollViewProxy can report which post is currently at the top.
  • scrollTo only works inside a List, not with a LazyVStack.

ScrollViewReader works on every iOS 17 and 18 device (it dates from iOS 14); scrollPosition(id:) needs iOS 17, ScrollPosition needs iOS 18, and one-parameter onChange is deprecated since iOS 17.