InfinityScrollKit
是一个 SwiftUI 包,它简化了 iOS 列表中无限滚动的实现。该包处理用户滚动时加载更多项目,同时为普通单元格和最后一个加载/错误状态单元格提供可自定义的 UI。
通过转到您的 Xcode 项目来添加包
+
按钮。InfinityScrollKit
https://github.com/PierreJanineh-com/InfinityScrollKit
如果您的项目中尚未使用 CocoaPods,请首先运行 sudo gem install cocoapods
,然后运行 pod init
。(有关安装 CocoaPods 的更多信息,点击此处。)
将以下内容添加到您的 Podfile(在 target 部分中)
pod 'InfinityScrollKit'
运行 pod install
。
请在此 repo 中查看完整示例。
下面是一个基本用法示例,我们在其中创建一个具有自定义项目和最后一个单元格视图的无限滚动列表
import SwiftUI
import InfiniteScrollView
struct ContentView: View {
@State private var items: [MyItem] = []
var body: some View {
InfiniteScrollView(
arr: $items,
cellView: { item in
Text(item.name) // Customize the view for each item
}
)
}
}
arr
: 要显示的项目的数组。cellView
: 一个 ViewBuilder
函数,用于显示列表中的单个单元格。onLoadingChange
: 一个闭包,用于在加载状态更改时通知父视图。options
: 您可以传递 Options<T>
来定制每页的项目数,并通过回调函数处理更多项目的加载。lastCellView
: 列表末尾视图的 ViewBuilder
函数(例如,加载指示器或错误消息)。emptyArrayView
: 自定义列表为空时显示的视图。import SwiftUI
import InfinityScrollKit
struct ContentView: View {
@State private var arr: [String] = []
@State private var isLoading: Bool = false
var body: some View {
InfiniteScrollView(
arr: $arr,
options: options,
onLoadingChanged: onLoadingChanged,
cellView: CellView,
lastCellView: LastCellView,
emptyArrView: EmptyArrView
)
// You can also use ScrollView modifiers directly
.scrollIndicators(.hidden)
}
private var options: Options<String> {
.init(
orientation: .horizontal,
countPerPage: 2,
paginationOptions: .init(
onPageLoad: {
// Replace this with an API pagination request
try? await Task.sleep(nanoseconds: 5 * 1_000_000_000)
var fetchedItems: [String]
// ...
// fetch additional items to add to the current array
return fetchedItems
},
concatMode: .auto //.auto for automatically adding pages to the array instead of passing the full array everytime.
)
)
}
private func onLoadingChanged(_ isLoading: Bool) {
self.isLoading = isLoading
if self.isLoading {
// Do anything here...
}
}
@ViewBuilder func CellView(_ item: String) -> some View {
Text(item)
}
@ViewBuilder func LastCellView() -> some View {
ProgressView()
.padding()
}
@ViewBuilder func EmptyArrView() -> some View {
Text("No items to display...")
}
}
InfiniteScrollView 包支持以下平台
欢迎通过创建 issue 或提交 pull request 来进行贡献。在提交之前,请确保
(git checkout -b feature/my-feature)
。(git commit -m 'Add some feature')
。(git push origin feature/my-feature)
。本项目根据 MIT 许可证获得许可。 有关更多详细信息,请参见 LICENSE 文件。