Home > Enterprise >  Is there a way to detect only the cells displayed on the screen when using List in SwiftUI?
Is there a way to detect only the cells displayed on the screen when using List in SwiftUI?

Time:05-30

Is it possible to detect the cell (or array position) of the List currently displayed on the View screen from among the 100 Items as shown below?

Also, at that time, I would like to get the position of the cell in detail, such as some cells that are half hidden from the screen at the top and bottom.

struct DemoList: View {
    // 1.
    @State private var items: [Item] = (0..<100).map { Item(title: "Item #\($0)") }

    // 2.
    var body: some View {
        List {
            ForEach(items) { item in
                Text(item.title)
            }
        }
    }
}

CodePudding user response:

Try using ‘onAppear’ modifier as Text(text).onAppear {} Since iOS 15 there have been improvements around that modifier

CodePudding user response:

This might be a starting point. But beware that List always keeps one "buffer" cell before .onAppear/.onDisappear kick in.

        List {
            ForEach(items) { item in
                GeometryReader { geo in
                    Text(item.title)
                        .onAppear {
                            print(item.title, geo.frame(in: .global))
                        }
                        .onDisappear {
                            print(item.title, "---")
                        }
                }
            }
        }

A more sophisticated approach would use PreferenceKey. I recommend this (look for "GridInfoPreference"): https://swiftui-lab.com/impossible-grids/

  • Related