0

I have a 2d ScrollView (vertical/horizontal) wrapped in a ScrollViewReader and populated by two ForEachs ... straight from the book.

Now the buttons don't scroll to the specified items, but strangely always to double of the row, i.e. 10_10 scrolls to 20_10, 20_20 scrolls to 40_20, 40_40 scrolls out of bounds??

What am I missing? Is it a macOS 12.2beta issue?

struct ContentView: View {
    
    var body: some View {
        ScrollViewReader { scrollProxy in
            VStack {
                HStack {
                    Button("10-10") {
                        withAnimation {
                            scrollProxy.scrollTo("10-10", anchor: .center)
                        }
                    }
                    Button("20-20") {
                        withAnimation {
                            scrollProxy.scrollTo("20-20", anchor: .center)
                        }
                    }
                    Button("40-40") {
                        withAnimation {
                            scrollProxy.scrollTo("40-40", anchor: .center)
                        }
                    }
                }
                ScrollView([.vertical, .horizontal]) {
                    VStack {
                        ForEach(0..<50) { row in
                            HStack {
                                ForEach(0..<50) { col in
                                    Rectangle()
                                        .fill(.gray)
                                        .overlay(
                                            Text("\(row)-\(col)").font(.caption)
                                        )
                                        .frame(width: 50, height: 50)
                                        .id("\(row)-\(col)")
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
ChrisR
  • 9,523
  • 1
  • 8
  • 26
  • 1
    Take a look at [this answer](https://stackoverflow.com/a/70177677/7129318). The problem is that when you are dealing with bidirectional `ScrollView`, the reader gets confused as to where you want it to go. You need to set an anchor for the correct corner, side or center, depending on where the `.scrollTo` is supposed to go. – Yrb Feb 09 '22 at 21:51
  • @Yrb wow! not so intuitive ;) – ChrisR Feb 09 '22 at 21:57
  • Not at all. I am not sure how I stumbled into that answer. I had only used single `ScrollViews` with `.scrollTos` before that. I think it was that you could move the scroll view to a side and it would work for that side. – Yrb Feb 09 '22 at 22:00

0 Answers0