How to Achieve Precise Scrolling using ScrollViewReader
2 min readSep 4, 2023
To programmatically scroll to a specific point, utilising the ScrollViewReader
along with its method scrollTo(_:anchor:)
is essential.
The scrollTo(_:anchor:)
method takes two parameters:
id
: identifier of the view to which the scroll will navigate.anchor
: optional parameter that determines the position of the view after the scroll operation concludes. It is of typeUnitPoint
, and you can experiment with the following options:
- zero
- center
- leading
- trailing
- top
- bottom
- topLeading
- topTrailing
- bottomLeading
- bottomTrailing
Example Demonstrating the Usage of ScrollViewReader
struct ContentView: View {
var body: some View {
ScrollViewReader { proxy in
// 1
ScrollView {
// 2
Button("Scroll to 23") {
withAnimation {
proxy.scrollTo(23, anchor: .top)
}
}
.padding()
// 3
ForEach(0..<100) { i in
Text("\(i)")
.font(.title2)
.frame(width: 100, height: 100)
.background(Color.blue)
.id(i)
}
}
}
}
}
- The first step is to enclose the
ScrollView
orList
within aScrollViewReader
. - Next, we create a button responsible for triggering the
scrollTo(_:anchor:)
action. In this instance, we specify that it should scroll to position 23 with animation and an anchor of.top
. This button is optional; you can execute the scroll without requiring user interaction. Simply call thescrollTo(_:anchor:)
method. - Finally, we generate a list of numbers ranging from 0 to 99 using a
ForEach
loop. The loop assigns the index of theForEach
as the item's identifier. Consequently, when callingscrollTo(_:anchor:)
for position 23, the system knows precisely where to scroll.
If you want to read the Spanish version of this article, you can find it here: https://asynclearn.com/blog/como-hacer-scroll-a-una-posicion-exacta-con-scrollviewreader