SwiftUI - ScrollViewReader's scrollTo does not scroll

I have a simple SwiftUI list that I want to scroll to a row when a user click on a button. This is my code that it suppose to work, but it does not do.
Code Block
struct ContentView: View {
var body: some View {
ScrollViewReader { proxy in
VStack {
Button("Jump to #50") {
proxy.scrollTo(5, anchor: .top)
}
List(0..<100) { i in
Text("Example \(i)")
.id(i)
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}


I tested it on iOS 14.2 both on simulator and a physical device.

I read srollTo's documentation) but there is not much info.

So how to scroll to a row, for example, row 50?


Accepted Reply

Seems your link to the document is sort of broken (not your fault, the markdown-like processor of this site is broken),
but it is true the documentation of scrollTo(_:anchor:) is quite unkind.

As far as I tried, ScrollViewReader works only with:
  • Explicit use of ScrollView

  • List of identifiable collection

And it does not work with List of Range<Int>.

Please try this:
Code Block
struct ContentView: View {
var body: some View {
ScrollViewReader { proxy in
VStack {
Button("Jump to #50") {
proxy.scrollTo(50, anchor: .top)
}
List(0..<100, id: \.self) { i in //<-
Text("Example \(i)")
.id(i)
}
}
}
}
}

(Please do not forget id: \.self on line 8, which makes List treat 0..<100 as an identifiable collection.)

I have found almost the same code on the web, so it may have once worked in a certain version of SwiftUI.

Replies

Seems your link to the document is sort of broken (not your fault, the markdown-like processor of this site is broken),
but it is true the documentation of scrollTo(_:anchor:) is quite unkind.

As far as I tried, ScrollViewReader works only with:
  • Explicit use of ScrollView

  • List of identifiable collection

And it does not work with List of Range<Int>.

Please try this:
Code Block
struct ContentView: View {
var body: some View {
ScrollViewReader { proxy in
VStack {
Button("Jump to #50") {
proxy.scrollTo(50, anchor: .top)
}
List(0..<100, id: \.self) { i in //<-
Text("Example \(i)")
.id(i)
}
}
}
}
}

(Please do not forget id: \.self on line 8, which makes List treat 0..<100 as an identifiable collection.)

I have found almost the same code on the web, so it may have once worked in a certain version of SwiftUI.
Thanks. It works after I added id: \.self 

That is a bug in Apple's Editor. Link is broken If it ends with )