0

I have a SwiftUI ScrollView that has different types of child views, I want to tap on a button to scroll to a particular view, I have tried ScrollViewReader and tagged each view with a unique integer but it doesn't work.

I made some progress by using introspect to get a reference to the underlying UIScrollView and let it scroll to a hardcoded yOffset, my question is: how can I get the yOffset for that particular view so that the scroll view can scroll to ?

The code:

ScrollView {
            VStack {
                Button {
                    scrollView?.setContentOffset(CGPoint(x: 0, y: 200), //<--- how to calculate yOffset for Circle #5
                                                 animated: true)
                } label: {
                    Text("Scroll to Circle 5")
                }

                ForEach(0..<20) { i in
                    Rectangle()
                        .fill(Color.gray)
                        .frame(height: 50)
                        .overlay(Text("Rectangle \(i)"))
                }
                
                Divider()
                    .padding()
                
                ForEach(0..<20) { i in
                    Circle()
                        .fill(Color.gray)
                        .frame(height: 60)
                        .overlay(Text("Circle \(i)"))
                }
                
            }
            .introspectScrollView { scrollView in
                self.scrollView = scrollView
            }
        }
JAHelia
  • 6,934
  • 17
  • 74
  • 134
  • 2
    Does this answer your question https://stackoverflow.com/a/62587784/12299030? Or https://stackoverflow.com/a/60855853/12299030? You definitely need ScrollViewReader, would you demo what's the problem with it? – Asperi Jul 03 '22 at 06:44
  • yes this answers my question, the problem was that I was using `.tag(5)` instead of `.id(5)`, thank you for your reference, you can mention the same answer (first link) here so that I will mark it as accepted answer – JAHelia Jul 03 '22 at 07:31

0 Answers0