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
}
}