With the release of iOS 14, there is a new ScrollViewReader which seems like it can read the current position. However, the docs around this are minimal, and do not explain how to do so. So, what is ScrollViewReader, and how can I get the current position of a scrollview?
You can get the position by using GeometryReader to read the scrollView content frame, pass the value using PreferenceKey and observe it:
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).
Code Block swift struct 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).