Skip to content

Instantly share code, notes, and snippets.

@jayesh15111988
Created April 30, 2023 10:10
Show Gist options
  • Save jayesh15111988/2ae29a34ce20a67dcc01ce11d46247b1 to your computer and use it in GitHub Desktop.
Save jayesh15111988/2ae29a34ce20a67dcc01ce11d46247b1 to your computer and use it in GitHub Desktop.
A SwiftUI, Swift and iOS source code to demonstrate working of infinite loading screen with pagination
//
// InfiniteLoadingScreen.swift
// Test
//
// Created by Jayesh Kawli on 1/12/23.
//
import SwiftUI
struct Employee: Identifiable, Equatable {
var id: String {
name
}
let name: String
}
class ViewModel: ObservableObject {
private let maximumNumberOfRecordsToFetch = 40
@Published var listItems: [Employee] = []
@Published var isLoading = true
private var iteration = 0
init() {
loadItems()
}
func loadItems() {
if iteration >= maximumNumberOfRecordsToFetch {
self.isLoading = false
return
}
// Artificial delay to give illusion of network service loading data
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
let employees = (self.iteration..<self.iteration + 10).map { Employee(name: String($0)) }
self.iteration += 10
self.listItems.append(contentsOf: employees)
}
}
}
struct InfiniteLoadingScreen: View {
@ObservedObject var viewModel = ViewModel()
var body: some View {
List {
ForEach(viewModel.listItems) { listItem in
Text(listItem.name)
if listItem == viewModel.listItems.last {
if viewModel.isLoading {
ProgressView().onAppear {
viewModel.loadItems()
}
}
}
}
}
}
}
struct InfiniteLoadingScreen_Previews: PreviewProvider {
static var previews: some View {
InfiniteLoadingScreen(viewModel: .init())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment