Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you implement list paging in SwiftUI or infinite list view?

I want help on how to implement infinite list scrolling or paging list in SwiftUI.Thanks in advance

like image 345
sualah abdullai Avatar asked Jan 01 '23 15:01

sualah abdullai


1 Answers

Your best bet is to use .onAppear and calculate if it's time to fetch your next page. This is a contrived example because typically you're hitting a network or disk which is much slower than this, but it will give you an idea. Tune getNextPageIfNecessary(_:) for your particular use-case.

@State var rows: [String] = Array(repeating: "Item", count: 20)

var body: some View {

    List(0..<rows.count, id: \.self) { index in
        Text(verbatim: self.rows[index])
            .onAppear {
                self.getNextPageIfNecessary(encounteredIndex: index)
            }
    }
}

private func getNextPageIfNecessary(encounteredIndex: Int) {
    guard encounteredIndex == rows.count - 1 else { return }

    rows.append(contentsOf: Array(repeating: "Item", count: 20))
}
like image 144
Procrastin8 Avatar answered Apr 27 '23 13:04

Procrastin8