I need to get the ScrollView value, and I already have one solution, but it's not very optimized. And I have a strong feeling that I'm missing a simpler solution. My final goal is get the ScrollView value to animate the closure of the block (as in the weather app from Apple). Please Help
There is no optimized solution here
ScrollView(.vertical, content: {
Vstack(content:{
Rectaingle()
.frame(width:100, height: 100)
})
.background(GeometryReader {
Color.clear.preference(key: ViewOffsetKey.self,
value: -$0.frame(in: .named("scroll")).origin.y)
})
.onPreferenceChange(ViewOffsetKey.self) {mainScrollValue = $0}
})
.coordinateSpace(name: "scroll")
.scrollIndicators(.never)
Working on IOS 16.0
I need to get the ScrollView value, and I already have one solution, but it's not very optimized. And I have a strong feeling that I'm missing a simpler solution. My final goal is get the ScrollView value to animate the closure of the block (as in the weather app from Apple). Please Help
There is no optimized solution here
ScrollView(.vertical, content: {
Vstack(content:{
Rectaingle()
.frame(width:100, height: 100)
})
.background(GeometryReader {
Color.clear.preference(key: ViewOffsetKey.self,
value: -$0.frame(in: .named("scroll")).origin.y)
})
.onPreferenceChange(ViewOffsetKey.self) {mainScrollValue = $0}
})
.coordinateSpace(name: "scroll")
.scrollIndicators(.never)
Working on IOS 16.0
Share Improve this question edited Jan 20 at 15:29 Jan Ivashenko asked Jan 20 at 0:52 Jan IvashenkoJan Ivashenko 35 bronze badges 7 | Show 2 more comments1 Answer
Reset to default 0If you are looking for a solution that involves less code then I would suggest using .onGeometryChange
. This is compatible with iOS 16:
struct ContentView: View {
@State private var scrollOffset = CGFloat.zero
var body: some View {
ScrollView {
VStack {
Rectangle()
.frame(width: 100, height: 100)
}
.onGeometryChange(for: CGFloat.self) { proxy in
proxy.frame(in: .named("scroll")).minY
} action: { minY in
scrollOffset = minY
}
}
.coordinateSpace(name: "scroll")
.scrollIndicators(.never)
}
}
.scrollPosition
. If your target is iOS 18 then there are some new features that might be useful, seeonScrollGeometryChange(for:of:action:)
– Benzy Neez Commented Jan 20 at 9:52.scrollPosition
is available in iOS 17, seescrollPosition(id:anchor:)
. If you're targeting iOS 16 then you can use.onGeometryChange
instead of aPreferenceKey
, at least. – Benzy Neez Commented Jan 20 at 15:52