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