
Scroll to a specific item using a ScrollViewReader
Learn how to programmatically jump to a specific item inside long scrollable content by using ScrollViewReader.
When your app displays long lists of content, letting users jump directly to a specific point can make navigation much smoother and more intuitive. Instead of manually scrolling through dozens or hundreds of items, they can tap a button and land exactly where they need to be.
To implement this kind of behavior while using a ScrollView
, what is needed is a ScrollViewReader
.
ScrollViewReader
is a container view that enables programmatic scrolling to a specific item inside a ScrollView
. It gives access to a proxy value, a ScrollViewProxy
, that allows to move to known child views by calling its scrollTo(_:anchor:)
method.
This is especially useful when:
- You want to create a “Scroll to Top” or “Jump to Item” button.
- You're responding to user actions, such as selecting a category.
- You need to highlight or focus on a specific part of your content.
Let’s implement it.
// 1.
ScrollViewReader { proxy in
// 2.
ScrollView {
// 3.
LazyVStack {
ForEach(0..<50) { x in
ZStack {
Rectangle()
.fill(colors.randomElement()?.opacity(0.7) ?? .gray)
.frame(width: 450, height: 70)
Text("\(x+1)")
.foregroundStyle(.white)
.fontWeight(.heavy)
}
// 4.
.id(x)
}
}
}
.padding(.bottom)
Button(action: {
// 5.
proxy.scrollTo(39, anchor: .center)
}, label: {
Text("Scroll to button n.40")
.fontWeight(.black)
}).buttonStyle(.borderedProminent)
}
- Create an instance of a
ScrollViewReader
. - Create an instance of a
ScrollView
. - Add the content.
- Use the
id(_:)
view method on each part of your content that needs to be scrollable to. It will bind the view’s identity to the given proxy value. - Create a button that calls
scrollTo(_:anchor:)
method on theproxy
value provided by theScrollViewReader
.
Scrolling to item 40
The method scrollTo(_:anchor:)
takes two parameters:
- the
id
of the view to scroll to. - the
anchor
, this defines how the item should be positioned after scrolling. It can be set on the following values:
It searches through all the scroll views managed by the proxy to find the first child view with the matching id, and then moves to that view, making it visible, and so placing it on the screen, accordingly to the type of provided anchor
value.
Scrolling to item 40 behavior based on different anchor values.
Adding programmatic scrolling with ScrollViewReader
gives you control over navigation inside long scrollable content. Whether you're helping users jump to a section, highlight an item, or return to the top with ease, it improves the user experience making it feel faster, smoother, and more interactive. With just a few lines of code, you can guide users exactly where they need to be.