You can get the position by using
GeometryReader to read the scrollView content frame, pass the value using
PreferenceKey and observe it:
Code Block swiftstruct ContentView: View { |
|
var body: some View { |
ScrollView { |
ZStack { |
LazyVStack { |
ForEach(0...100, id: \.self) { index in |
Text("Row \(index)") |
} |
} |
GeometryReader { proxy in |
let offset = proxy.frame(in: .named("scroll")).minY |
Color.clear.preference(key: ScrollViewOffsetPreferenceKey.self, value: offset) |
} |
} |
} |
.coordinateSpace(name: "scroll") |
.onPreferenceChange(ScrollViewOffsetPreferenceKey.self) { value in |
print(value) |
} |
} |
|
} |
The
.frame(in: .named("scroll")) is required to get the
frame relative to the
ScrollView and obtain a 0 offset when at the top, without the height of the safe area. If you try using
.frame(in: .global) you will get a non-zero value when the scroll view is at the top (20 or 44, depends on the device).