I have found a way to save a ScrollViews offset with a GeometryReader
and a PreferenceKey
.
SwiftUI | Get current scroll position from ScrollView
And the ScrollViewReader
has a method scrollTo
to scroll to a set position.
scrollTo
The problem is, that the first one saves an offset while the second method expects a position (or an id, which is similar to the position in my case). How can I convert the offset to a position/id or is there any other way to save and load a ScrollViews position?
Here is the code I have now but it does not scroll the way I want:
ScrollView {
ScrollViewReader { scrollView in
LazyVGrid(columns: columns, spacing: 0) {
ForEach(childObjects, id: .id) { obj in
CustomView(obj: obj).id(obj.id)
}
}
.onChange(of: scrollTarget) { target in
if let target = target {
scrollTarget = nil
scrollView.scrollTo(target, anchor: .center)
}
}
.background(GeometryReader {
Color.clear.preference(key: ViewOffsetKey.self,
value: -$0.frame(in: .named("scroll")).origin.y)
})
.onPreferenceChange(ViewOffsetKey.self) { // save $0 }
}
}.coordinateSpace(name: "scroll")
And in the onAppear
of the View I want to set scrollTarget
to the saved position. But it scrolls anywhere but not to the position I want.
I thought about dividing the offset by the size of one item but is that really the way to go? It does not sound very good.
question from:
https://stackoverflow.com/questions/65870891/save-scrollviews-position-and-scroll-back-to-it-later-offset-to-position 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…