Home > Enterprise >  LazyVStack - row onAppear is called early
LazyVStack - row onAppear is called early

Time:11-29

I have a LazyVStack, with lots of rows. Code:

struct ContentView: View {
    var body: some View {
        ScrollView {
            LazyVStack {
                ForEach(0 ..< 100) { i in
                    Text("Item: \(i   1)")
                        .onAppear {
                            print("Appeared:", i   1)
                        }
                }
            }
        }
    }
}

Only about 40 rows are visible on the screen initially, yet onAppear is triggered for 77 rows. Why is this, why is it called before it is actually visible on the screen? I don't see why SwiftUI would have to 'preload' them.

Is there a way to fix this, or if this is intended, how can I accurately know the last visible item (accepting varying row heights)?

Edit

The enter image description here

It works as per my comments above.

struct ContentView: View {
    var body: some View {
        ScrollView {
            LazyVStack {
                ForEach(0 ..< 100) { i in
                    Text("Item: \(i   1)")
                        .id(i)
                        .frame(width: 100, height: 100)
                        .padding()
                        .onAppear { print("Appeared:", i   1) }
                }
            }
        }
    }
}
  • Related