SwiftUI ScrollView scrolls too far when using scrollViewReader
Asked Answered
C

0

8

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.

Cacomistle answered 12/3, 2021 at 15:17 Comment(2)
The 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 use anchor.Stortz
Have you found an answer? I'm facing the same problem...Euphoria

© 2022 - 2024 — McMap. All rights reserved.