0

What is the best way to detect when a user has scrolled to the bottom of the screen and trigger a specific function in SwiftUI?

var body: some View {
    NavigationView {
        VStack {
            ZStack {
                Text("Pokedex")
                    .font(.custom("Pokemon Solid", size: 25))
                    .foregroundColor(.yellow)
                    .opacity(0.3)
                GeometryReader { geometry in
                    ScrollView {
                        LazyVGrid(columns: adaptiveColumns, spacing: 5) {
                            ForEach(viewModel.filteredPokemon) { pokemon in
                                NavigationLink(destination: PokemonDetailView(pokemon: pokemon)
                                ) {
                                    PokemonView(vm: viewModel, pokemon: pokemon)
                                }
                            }
                        }
                        .animation(.easeInOut(duration: 0.3), value: viewModel.filteredPokemon.count)
                        .navigationTitle("Pokedexarino")
                        .navigationBarTitleDisplayMode(.inline)

                        if geometry.frame(in: .global).maxY == geometry.safeAreaInsets.bottom {
                            Text("Reached the bottom")
                            //TODO: make load 30 at a time
                            
                        }
                    }
                }
                .searchable(text: $viewModel.searchText)
            }
        }
    }
    .environmentObject(viewModel)
}

I tried to create a function but I think there may be a built in function that can do this. I tried Geometry reader.

burnsi
  • 6,194
  • 13
  • 17
  • 27

1 Answers1

0

You can add paging to your ScrollView by displaying an additional row at the bottom if more data is available, then using the .task modifier to load the next page, e.g.

ScrollView {
    LazyVGrid(columns: adaptiveColumns, spacing: 5) {
        ForEach(viewModel.filteredPokemon) { pokemon in
            NavigationLink(destination: PokemonDetailView(pokemon: pokemon)
            ) {
                PokemonView(vm: viewModel, pokemon: pokemon)
            }
        }
        if viewModel.moreDataAvailable {
            Text("Reached the bottom")
                .task {
                    await viewModel.loadNextPage()
                }
        }
    }
}

Ashley Mills
  • 50,474
  • 16
  • 129
  • 160