I'm creating an app where I'm presenting data in paged views and each view contains a vertical scrollable list, enabled by scrollView. I'm also using scrollViewReader to be able to programmatically scroll to a specific position in the list. This works OK in most cases, but when I programmatically scroll to the bottom of the list (to the last item), it scrolls too far.
I have isolated a case where this is repeatable:
ScrollView(.vertical, showsIndicators: false) {
ScrollViewReader { scrollView in
LazyVStack(alignment: .leading) {
ForEach((1..<100) , id:\.self) { key in
Text("Hello \(key)")
}
}
.onAppear {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
withAnimation {
scrollView.scrollTo(99, anchor: .center)
}
}
}
}
}
If you run this on e.g. the iPhone 12 simulator, you will se that the last item in the list ends up in the middle of the screen. If you manually scroll and release, the list will "fall down" to the bottom of the screen, which is the position I want the list to have even though I scroll to the last item with .anchor: .center
.
Is there some way around this behavior?
Edit: Realized I wasn't clear enough. I want the anchor to be .center as long as I have more scrollable content in my view. But when I get to the bottom of the list I want the scrollView to be smart enough to know that it's not possible to scroll any longer. As it is now, it scrolls more than is possible if you scroll manually.
anchor
parameter behaves as documented, ie ScrollViewReader is smart enough to do what you asked by interface contract. If you want different behaviour don't useanchor
. – Stortz