0

I'm presenting a dynamic table that can expand from the top or bottom. When presenting data in a combination of ScrollView and LazyVGrid, if I add more data to the bottom the scroll view doesn't change (this is what I want). However when data is added to the top of the list, the scrollview moves to the relative same position as before (but now displaced by the amount of new elements) instead of staying at the same position.

I could easily fix this behaviour if I could know the current visible position so after adding more data I could use .scrollTo (oldPosition + additionalElements). However I can't find a way to get this value.

In the following View you can see the behaviour:

import SwiftUI

struct ContentView: View {
    
    @State var table: [Int] = Array(100...200)

    var body: some View {
        VStack {
            HStack {
                Button {
                    let temp = Array(90...99)
                    self.table = temp + self.table
                } label: {
                    Text("Add 10 on top. It will displace ScrollView")
                }
                
                Button {
                    let temp = Array(201...210)
                    self.table = self.table + temp
                } label: {
                    Text("Add 10 to the bottom. It will not move ScrollView")
                }
            }
            
            ScrollViewReader { reader in
                ScrollView {
                    LazyVGrid(columns: [GridItem()], alignment: .center, spacing: 0.0) {
                        ForEach(table, id: \.self) { i in
                            Text("\(i)")
                        }
                    }
                    .onAppear {
                        reader.scrollTo(150, anchor: .center)
                    }
                }
            }
        }
        .padding()
    }
}

Any idea how to get this value?

How to get current position of LazyVGrid?

0 Answers0