ScrollViewReader not scrolling to the correct id with anchor

Viewed 36

Problem

  • First time when the button "Go to 990" is tapped the scroll view doesn't scroll to 990 on top. (see screenshot below)
  • The anchor is not respected.
  • Second time it scrolls to 990 top correctly.

Questions

  1. What is wrong and how can it be fixed?

Versions

  • Xcode 14

Code

struct ContentView: View {
    
    @State private var scrollProxy: ScrollViewProxy?
    
    var body: some View {
        NavigationStack {
            ScrollViewReader { proxy in
                List(0..<1000, id: \.self) { index in
                    VStack(alignment: .leading) {
                        Text("cell \(index)")
                            .font(.title)
                        Text("text 1")
                            .font(.subheadline)
                        Text("text 2")
                            .font(.subheadline)
                    }
                }
                .onAppear {
                    scrollProxy = proxy
                }
            }
            .toolbar {
                ToolbarItem {
                    Button("Go to 990") {
                        scrollProxy?.scrollTo(990, anchor: .top)
                    }
                }
            }
        }
        #if os(macOS)
        .frame(minWidth: 500, minHeight: 300)
        #endif
    }
}

Screenshot

After tapping on Go to 990, doesn't scroll to 990 top

0 Answers
Related