How to Achieve Precise Scrolling using ScrollViewReader

AsyncLearn
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 type UnitPoint, 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)
}
}
}
}
}
  1. The first step is to enclose the ScrollView or List within a ScrollViewReader.
  2. 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 the scrollTo(_:anchor:) method.
  3. Finally, we generate a list of numbers ranging from 0 to 99 using a ForEach loop. The loop assigns the index of the ForEach as the item's identifier. Consequently, when calling scrollTo(_: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

--

--

AsyncLearn
AsyncLearn

Written by AsyncLearn

Stay up-to-date in the world of mobile applications with our specialised blog.

No responses yet