how to add pageable content to scrollview in swiftui in swift

To add pageable content to ScrollView in SwiftUI, we can use LazyVStack and onChange(of: perform:) methods. Here is an example:

main.swift
struct ContentView: View {
    let pageSize = 20 // Number of items per page
    @State private var currentPage = 0
    @State private var items = Array(1...100) // Some items to display
    
    var body: some View {
        ScrollView {
            LazyVStack {
                ForEach(pagedItems, id: \.self) { item in
                    Text(String(item))
                        .padding()
                }
            }
            .onChange(of: currentPage, perform: { value in
                // Load the next page when current page changes
                fetchNextPage()
            })
        }
    }
    
    // Calculate paged items based on current page
    var pagedItems: [Int] {
        Array(items[currentPage * pageSize ..< (currentPage + 1) * pageSize])
    }
    
    // Fetch the next page
    func fetchNextPage() {
        // Do some API call or local data loading
        // ...
        // Update items
        items.append(contentsOf: Array(items.count + 1 ... items.count + pageSize))
    }
}
1022 chars
34 lines

In the above example, we have used LazyVStack to display the items instead of List to have more control over the pagination. The onChange method is used to load the next page when the current page changes. The pagedItems computed property is used to calculate the items to display based on the current page and page size. Finally, the fetchNextPage method is used to simulate loading the next page from an API call or local data.

related categories

gistlibby LogSnag