Hello,
I want to detect when a ScrollView is scrolled at the top of a specific View in a LazyVStack. Here is the code I use:
struct ContentView: View {
@State private var scrollID: Int?
var body: some View {
HStack {
VStack {
Text(scrollID?.formatted() ?? "Unknown")
Button("Go") {
withAnimation {
scrollID = 7
}
}
Divider()
ScrollView {
LazyVStack(spacing: 300) {
ForEach(0...100, id: \.self) { int in
Text(int.formatted())
.frame(maxWidth: .infinity)
.background(.red)
}
}
.scrollTargetLayout()
}
.scrollPosition(id: $scrollID, anchor: .top)
}
}
}
}
As I specify a top anchor, I was expecting to see the scrollID
binding being updated when the red Text View is at the top of the ScrollView. But I noticed that scrollPosition updates the binding way before the red Text View is positioned at the top of the ScrollView, which is not what I want.
In this image, you can see the binding is already at one even though there is a lot of space between the View and the top of the ScrollView. Maybe the Stack spacing is taken into account?
And manually setting the binding scroll at the position I want, just above the red Text for 7, which makes me think the views IDs are correct.
Is my understanding wrong about this modifier?
How can I detect the top (beginning) of the View?
(If this is a SwiftUI bug, I filed #FB13811349)