如何在 SwiftUI 中使用无限数量的项目制作无限 ScrollView
How to make infinite ScrollView with infinite amount of items in SwiftUI
我是 IOS 和 SwiftUI 的新手,所以请纠正我所做的任何错误假设。
我需要在 SwiftUI 中创建一个与 android 中的 RecyclerView
具有相似功能的视图。
具体来说,我要制作的是水平 ScrollView
,其中显示的项目(位于屏幕中央的项目)由其索引构成。
例如,如果我正在查看索引 0,那么它将在 ie 中显示带有一些日期文本的卡片(2022 年 1 月 1 日)
那么索引 1 将显示 2022 年 1 月 2 日,索引 2 将显示 2022 年 1 月 3 日等...
所以你可以看到,如果用户想要滚动得足够远,理论上它可以永远持续下去。
因此,我无法创建对象列表并在 HStack
中循环遍历它们。所以我想要某种功能,我只创建 3 张卡片,然后当我向右滚动并且索引 0 卡片看不见时,它被重新用作 'new' 卡片的右侧(末尾) ScrollView
。与 RecyclerView
.
相同的行为
最重要的是我需要能够访问特定渲染卡的索引,否则我无法构建我的数据。
可以使用LazyHGrid实现RecyclerView功能
struct ContentView: View {
// MARK: - PROPERTIES
let gridItems = [
GridItem(.flexible()),
GridItem(.flexible())
]
var body: some View{
ScrollView(.horizontal, showsIndicators: false) {
LazyHGrid(rows: gridItems, alignment: .center, spacing: 10) {
ForEach(0...10, id: \.self){ number in
// You can create your own ReusableView and put it here
Text("\(number)")
.frame(width: 100)
.background(.blue)
}
}
}
.frame(height: 100)
}
}
// MARK: - PREVIEW
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
我是 IOS 和 SwiftUI 的新手,所以请纠正我所做的任何错误假设。
我需要在 SwiftUI 中创建一个与 android 中的 RecyclerView
具有相似功能的视图。
具体来说,我要制作的是水平 ScrollView
,其中显示的项目(位于屏幕中央的项目)由其索引构成。
例如,如果我正在查看索引 0,那么它将在 ie 中显示带有一些日期文本的卡片(2022 年 1 月 1 日)
那么索引 1 将显示 2022 年 1 月 2 日,索引 2 将显示 2022 年 1 月 3 日等...
所以你可以看到,如果用户想要滚动得足够远,理论上它可以永远持续下去。
因此,我无法创建对象列表并在 HStack
中循环遍历它们。所以我想要某种功能,我只创建 3 张卡片,然后当我向右滚动并且索引 0 卡片看不见时,它被重新用作 'new' 卡片的右侧(末尾) ScrollView
。与 RecyclerView
.
最重要的是我需要能够访问特定渲染卡的索引,否则我无法构建我的数据。
可以使用LazyHGrid实现RecyclerView功能
struct ContentView: View {
// MARK: - PROPERTIES
let gridItems = [
GridItem(.flexible()),
GridItem(.flexible())
]
var body: some View{
ScrollView(.horizontal, showsIndicators: false) {
LazyHGrid(rows: gridItems, alignment: .center, spacing: 10) {
ForEach(0...10, id: \.self){ number in
// You can create your own ReusableView and put it here
Text("\(number)")
.frame(width: 100)
.background(.blue)
}
}
}
.frame(height: 100)
}
}
// MARK: - PREVIEW
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}