Advanced List View for SwiftUI with pagination & different states

Overview

AdvancedList

Swift 5.3 Platforms Current version Build status Code coverage License

This package provides a wrapper view around the SwiftUI List view which adds pagination (through my ListPagination package) and an empty, error and loading state including a corresponding view.

📦 Installation

Add this Swift package in Xcode using its Github repository url. (File > Swift Packages > Add Package Dependency...)

🚀 How to use

The AdvancedList view is similar to the List and ForEach views. You have to pass data (RandomAccessCollection) and a view provider ((Data.Element) -> some View) to the initializer. In addition to the List view the AdvancedList expects a list state and corresponding views. Modify your data anytime or hide an item through the content block if you like. The view is updated automatically 🎉 .

import AdvancedList

@State private var listState: ListState = .items

AdvancedList(yourData, content: { item in
    Text("Item")
}, listState: listState, emptyStateView: {
    Text("No data")
}, errorStateView: { error in
    Text(error.localizedDescription)
        .lineLimit(nil)
}, loadingStateView: {
    Text("Loading ...")
})

🆕 Custom List view

Starting from version 6.0.0 you can use a custom list view instead of the SwiftUI List used under the hood. As an example you can now easily use the LazyVStack introduced in iOS 14 if needed.

Upgrade from version 5.0.0 without breaking anything. Simply add the listView parameter after the upgrade:

AdvancedList(yourData, listView: { rows in
    if #available(iOS 14, macOS 11, *) {
        ScrollView {
            LazyVStack(alignment: .leading, content: rows)
                .padding()
        }
    } else {
        List(content: rows)
    }
}, content: { item in
    Text("Item")
}, listState: listState, emptyStateView: {
    Text("No data")
}, errorStateView: { error in
    Text(error.localizedDescription)
        .lineLimit(nil)
}, loadingStateView: {
    Text("Loading ...")
})

📄 Pagination

The Pagination functionality is now (>= 5.0.0) implemented as a modifier. It has three different states: error, idle and loading. If the state of the Pagination changes the AdvancedList displays the view created by the view builder of the specified pagination object (AdvancedListPagination). Keep track of the current pagination state by creating a local state variable (@State) of type AdvancedListPaginationState. Use this state variable in the content ViewBuilder of your pagination configuration object to determine which view should be displayed in the list (see the example below).

If you want to use pagination you can choose between the lastItemPagination and the thresholdItemPagination. Both concepts are described here. Just specify the type of the pagination when adding the .pagination modifier to your AdvancedList.

The view created by the content ViewBuilder of your pagination configuration object will only be visible below the List if the last item of the List appeared! That way the user is only interrupted if needed.

Example:

@State private var paginationState: AdvancedListPaginationState = .idle

AdvancedList(...)
.pagination(.init(type: .lastItem, shouldLoadNextPage: {
    paginationState = .loading
    DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
        items.append(contentsOf: moreItems)
        paginationState = .idle
    }
}) {
    switch paginationState {
    case .idle:
        EmptyView()
    case .loading:
        if #available(iOS 14.0, *) {
            ProgressView()
        } else {
            Text("Loading ...")
        }
    case let .error(error):
        Text(error.localizedDescription)
    }
})

📁 Move and 🗑️ delete items

To enable the move or delete function just use the related onMove or onDelete view modifier. Per default the functions are disabled if you don't add the view modifiers.

import AdvancedList

@State private var listState: ListState = .items

AdvancedList(yourData, content: { item in
    Text("Item")
}, listState: listState, emptyStateView: {
    Text("No data")
}, errorStateView: { error in
    Text(error.localizedDescription)
        .lineLimit(nil)
}, loadingStateView: {
    Text("Loading ...")
})
.onMove { (indexSet, index) in
    // move me
}
.onDelete { indexSet in
    // delete me
}

🎛️ Filtering

You can hide items in your list through the content block. Only return a view in the content block if a specific condition is met.

🎁 Example

The following code shows how easy-to-use the view is:

import AdvancedList

@State private var listState: ListState = .items

AdvancedList(yourData, content: { item in
    Text("Item")
}, listState: listState, emptyStateView: {
    Text("No data")
}, errorStateView: { error in
    VStack {
        Text(error.localizedDescription)
            .lineLimit(nil)
        
        Button(action: {
            // do something
        }) {
            Text("Retry")
        }
    }
}, loadingStateView: {
    Text("Loading ...")
})

For more examples take a look at AdvancedList-SwiftUI.

Migration

Migration 2.x -> 3.0

The AdvancedList was dramatically simplified and is now more like the List and ForEach SwiftUI views.

  1. Delete your list service instances and directly pass your data to the list initializer
  2. Create your views through a content block (initializer parameter) instead of conforming your items to View directly (removed type erased wrapper AnyListItem)
  3. Pass a list state binding to the initializer (before: the ListService managed the list state)
  4. Move and delete: Instead of setting AdvancedListActions on your list service just pass a onMoveAction and/or onDeleteAction block to the initializer

Before:

import AdvancedList

let listService = ListService()
listService.supportedListActions = .moveAndDelete(onMove: { (indexSet, index) in
    // please move me
}, onDelete: { indexSet in
    // please delete me
})
listService.listState = .loading

AdvancedList(listService: listService, emptyStateView: {
    Text("No data")
}, errorStateView: { error in
    VStack {
        Text(error.localizedDescription)
            .lineLimit(nil)
        
        Button(action: {
            // do something
        }) {
            Text("Retry")
        }
    }
}, loadingStateView: {
    Text("Loading ...")
}, pagination: .noPagination)

listService.listState = .loading
// fetch your items ...
listService.appendItems(yourItems)
listService.listState = .items

After:

import AdvancedList

@State private var listState: ListState = .items

AdvancedList(yourData, content: { item in
    Text("Item")
}, listState: $listState, onMoveAction: { (indexSet, index) in
    // move me
}, onDeleteAction: { indexSet in
    // delete me
}, emptyStateView: {
    Text("No data")
}, errorStateView: { error in
    VStack {
        Text(error.localizedDescription)
            .lineLimit(nil)
        
        Button(action: {
            // do something
        }) {
            Text("Retry")
        }
    }
}, loadingStateView: {
    Text("Loading ...")
}, pagination: .noPagination)
Migration 3.0 -> 4.0

Thanks to a hint from @SpectralDragon I could refactor the onMove and onDelete functionality to view modifiers.

Before:

import AdvancedList

@State private var listState: ListState = .items

AdvancedList(yourData, content: { item in
    Text("Item")
}, listState: $listState, onMoveAction: { (indexSet, index) in
    // move me
}, onDeleteAction: { indexSet in
    // delete me
}, emptyStateView: {
    Text("No data")
}, errorStateView: { error in
    VStack {
        Text(error.localizedDescription)
            .lineLimit(nil)
        
        Button(action: {
            // do something
        }) {
            Text("Retry")
        }
    }
}, loadingStateView: {
    Text("Loading ...")
}, pagination: .noPagination)

After:

import AdvancedList

@State private var listState: ListState = .items

AdvancedList(yourData, content: { item in
    Text("Item")
}, listState: $listState, emptyStateView: {
    Text("No data")
}, errorStateView: { error in
    VStack {
        Text(error.localizedDescription)
            .lineLimit(nil)
        
        Button(action: {
            // do something
        }) {
            Text("Retry")
        }
    }
}, loadingStateView: {
    Text("Loading ...")
}, pagination: .noPagination)
.onMove { (indexSet, index) in
    // move me
}
.onDelete { indexSet in
    // delete me
}
Migration 4.0 -> 5.0

Pagination is now implemented as a modifier 💪 And last but not least the code documentation arrived 😀

Before:

private lazy var pagination: AdvancedListPagination<AnyView, AnyView> = {
    .thresholdItemPagination(errorView: { error in
        AnyView(
            VStack {
                Text(error.localizedDescription)
                    .lineLimit(nil)
                    .multilineTextAlignment(.center)

                Button(action: {
                    // load current page again
                }) {
                    Text("Retry")
                }.padding()
            }
        )
    }, loadingView: {
        AnyView(
            VStack {
                Divider()
                Text("Loading...")
            }
        )
    }, offset: 25, shouldLoadNextPage: {
        // load next page
    }, state: .idle)
}()

@State private var listState: ListState = .items

AdvancedList(yourData, content: { item in
    Text("Item")
}, listState: $listState, emptyStateView: {
    Text("No data")
}, errorStateView: { error in
    VStack {
        Text(error.localizedDescription)
            .lineLimit(nil)
        
        Button(action: {
            // do something
        }) {
            Text("Retry")
        }
    }
}, loadingStateView: {
    Text("Loading ...")
}, pagination: pagination)

After:

@State private var listState: ListState = .items
@State private var paginationState: AdvancedListPaginationState = .idle

AdvancedList(yourData, content: { item in
    Text("Item")
}, listState: $listState, emptyStateView: {
    Text("No data")
}, errorStateView: { error in
    VStack {
        Text(error.localizedDescription)
            .lineLimit(nil)
        
        Button(action: {
            // do something
        }) {
            Text("Retry")
        }
    }
}, loadingStateView: {
    Text("Loading ...")
})
.pagination(.init(type: .lastItem, shouldLoadNextPage: {
    paginationState = .loading
    DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
        items.append(contentsOf: moreItems)
        paginationState = .idle
    }
}) {
    switch paginationState {
    case .idle:
        EmptyView()
    case .loading:
        if #available(iOS 14.0, *) {
            ProgressView()
        } else {
            Text("Loading ...")
        }
    case let .error(error):
        Text(error.localizedDescription)
    }
})
Migration 6.0 -> 7.0

I replaced the unnecessary listState Binding and replaced it with a simple value parameter.

Before:

import AdvancedList

@State private var listState: ListState = .items

AdvancedList(yourData, content: { item in
    Text("Item")
}, listState: $listState, emptyStateView: {
    Text("No data")
}, errorStateView: { error in
    VStack {
        Text(error.localizedDescription)
            .lineLimit(nil)
        
        Button(action: {
            // do something
        }) {
            Text("Retry")
        }
    }
}, loadingStateView: {
    Text("Loading ...")
}, pagination: .noPagination)

After:

import AdvancedList

@State private var listState: ListState = .items

AdvancedList(yourData, content: { item in
    Text("Item")
}, listState: listState, emptyStateView: {
    Text("No data")
}, errorStateView: { error in
    VStack {
        Text(error.localizedDescription)
            .lineLimit(nil)
        
        Button(action: {
            // do something
        }) {
            Text("Retry")
        }
    }
}, loadingStateView: {
    Text("Loading ...")
}, pagination: .noPagination)
You might also like...
Elimination-backoff stack is an unbounded lock-free LIFO linked list, that eliminates concurrent pairs of pushes and pops with exchanges.

Elimination-backoff stack is an unbounded lock-free LIFO linked list, that eliminates concurrent pairs of pushes and pops with exchanges. It uses compare-and-set (CAS) atomic operation to provide concurrent access with obstruction freedom. In order to support even greater concurrency, in case a push/pop fails, it tries to pair it with another pop/push to eliminate the operation through exchange of values.

A paging scroll view for SwiftUI, using internal SwiftUI components
A paging scroll view for SwiftUI, using internal SwiftUI components

PagingView A paging scroll view for SwiftUI, using internal SwiftUI components. This is basically the same as TabView in the paging mode with the inde

SwiftUI-Margin adds a margin() viewModifier to a SwiftUI view.

SwiftUI-Margin adds a margin() viewModifier to a SwiftUI view. You will be able to layout the margins in a CSS/Flutter-like.

A way to quickly add a notification badge icon to any view. Make any view of a full-fledged animated notification center.
A way to quickly add a notification badge icon to any view. Make any view of a full-fledged animated notification center.

BadgeHub A way to quickly add a notification badge icon to any view. Demo/Example For demo: $ pod try BadgeHub To run the example project, clone the r

Confetti View lets you create a magnificent confetti view in your app
Confetti View lets you create a magnificent confetti view in your app

ConfettiView Confetti View lets you create a magnificent confetti view in your app. This was inspired by House Party app's login screen. Written in Sw

A SwiftUI Library for creating resizable partitions for View Content.
A SwiftUI Library for creating resizable partitions for View Content.

Partition Kit Recently Featured In Top 10 Trending Android and iOS Libraries in October and in 5 iOS libraries to enhance your app! What is PartitionK

📖   A lightweight, paging view solution for SwiftUI
📖 A lightweight, paging view solution for SwiftUI

Getting Started | Customization | Installation Getting Started Basic usage Using Pages is as easy as: import Pages struct WelcomeView: View { @S

SwiftUI view enabling navigation between pages of content, imitating the behaviour of UIPageViewController for iOS and watchOS
SwiftUI view enabling navigation between pages of content, imitating the behaviour of UIPageViewController for iOS and watchOS

PageView SwiftUI view enabling page-based navigation, imitating the behaviour of UIPageViewController in iOS. Why SwiftUI doesn't have any kind of pag

🚀  Elegant Pager View fully written in pure SwiftUI.
🚀 Elegant Pager View fully written in pure SwiftUI.

PagerTabStripView Made with ❤️ by Xmartlabs team. XLPagerTabStrip for SwiftUI! Introduction PagerTabStripView is the first pager view built in pure Sw

Comments
  • Love it, but modifiers..

    Love it, but modifiers..

    I think, that will good solutions using a modifiers instead of closures in init method. It'll more flexible and SwiftUI-like.

    Examples: Pretty modifiers for custom view. https://github.com/onevcat/Kingfisher/blob/master/Sources/SwiftUI/KFImage.swift

    Pure SwiftUI modifiers: https://github.com/SwiftUIExtensions/Grid

    opened by SpectralDragon 2
  • Scroll to the bottom when new element is added in the list ?

    Scroll to the bottom when new element is added in the list ?

    Hi, I stumbled upon this awesome library which does solve a lot of issues which are yet to be perfected by apple SwiftUI team, but the main problem which I was having is, I am building a chat screen in my app and cannot scroll to the bottom when a new chat is added in the list, I tried my own way of making a custom scroll view but I am worried that it might have a lot of performance issues and is not that optimized.

    opened by divyanshunegi 1
  • LoadingView improvement

    LoadingView improvement

    Is it possible to move the pagination LoadingView such that it appears below all list items?

    Now, as you see in the video, it seems to appear as an overlay on top of the elements. https://user-images.githubusercontent.com/82878359/207847254-892f9703-0295-4905-8652-a3c8cff80388.mov

    opened by Alex-Casale 0
Releases(8.0.0)
  • 8.0.0(Apr 10, 2022)

    No breaking changes

    But because of a refactoring under the hood I decided to make a new major release.

    Features

    • New APIs which mimic some SwiftUI List APIs
    • More freedom & control through the new custom content view API (checkout the Content example): Allows using ANY view you want as the list view: use a SwiftUI List or a custom view

    More

    Source code(tar.gz)
    Source code(zip)
  • 7.0.0(Apr 20, 2021)

  • 6.0.0(Nov 2, 2020)

  • 5.0.0(Aug 2, 2020)

    Swift 5.3

    Make use of some enhancements made in Swift 5.3, like the ones made to function builders.

    Pagination modifier 🚀

    The pagination functionality feels now more like native SwiftUI. Easily add pagination support to your AdvancedList with the new .pagination modifier. Don't forget to read the migration section in the README.

    Improvements & Refactoring

    • Say hello to code documentation 😀
    • Removed unnecessary self
    • Use @ViewBuilder instead of Group
    • Improved code indentation
    Source code(tar.gz)
    Source code(zip)
  • 4.0.1(Feb 22, 2020)

    4.0.1

    Changes

    • Got rid off AnyViews and switch statement in AdvancedList view implementation
    • Uses the Group view with if statements and a map now
    Source code(tar.gz)
    Source code(zip)
Owner
Chris
iOS Software Engineer @eos-uptrade
Chris
A UIControl subclass that makes it easy to create empty states.

AZEmptyState Making empty state simple. Screenshots Installation Cocoa Pods: pod 'AZEmptyState' Manual: Simply drag and drop the Sources folder to you

Antonio Zaitoun 88 Oct 2, 2022
Demonstrate the toolbar view modifier for SwiftUI with different placements

ToolbarProject Demonstrate the toolbar view modifier for SwiftUI with different placements Youtube tutorial --> https://youtu.be/jTW5Z-kyL8g Use toolb

Karin Prater 2 Mar 24, 2022
A drop-in universal library helps you to manage the navigation bar styles and makes transition animations smooth between different navigation bar styles

A drop-in universal library helps you to manage the navigation bar styles and makes transition animations smooth between different navigation bar styles while pushing or popping a view controller for all orientations. And you don't need to write any line of code for it, it all happens automatically.

Zhouqi Mo 3.3k Dec 21, 2022
A little app which shows different ways to simulate NSPanel using NSWindow

FunWithPanels A little app which shows different ways to simulate NSPanel using NSWindow, for better or worse. Settings FunWithPanels uses a combinati

Mitchell Cohen 7 Aug 3, 2022
A custom UIControl which functions like UISlider where you can set multiple intervals with different step values for each interval.

MultiStepSlider A custom UIControl which functions like UISlider where you can set multiple intervals with different step values for each interval. Th

Susmita Horrow 25 Apr 28, 2022
Simple and highly customizable iOS tag list view, in Swift.

TagListView Simple and highly customizable iOS tag list view, in Swift. Supports Storyboard, Auto Layout, and @IBDesignable. Usage The most convenient

Ela Workshop 2.5k Jan 5, 2023
A controller that uses a UIStackView and view controller composition to display content in a list

StackViewController Overview StackViewController is a Swift framework that simplifies the process of building forms and other static content using UIS

Seed 867 Dec 27, 2022
List tree data souce to display hierachical data structures in lists-like way. It's UI agnostic, just like view-model and doesn't depend on UI framework

SwiftListTreeDataSource List tree data souce to display hierachical data structures in lists-like way. It's UI agnostic, just like view-model, so can

Dzmitry Antonenka 26 Nov 26, 2022
Reel Search is a Swift UI controller that allows you to choose options from a list

REEL SEARCH Reel Search is a Swift UI controller that allows you to choose options from a list We specialize in the designing and coding of custom UI

Ramotion 2.5k Dec 21, 2022
Fetch the star wars api from all the planets and list and show details using Swift UI and Combine

Star Wars Planets Fetch the star wars planet data by using stat war api, list and show details using SwiftUI and Combine frameworks ?? Swift UI Framew

null 1 Aug 10, 2022