分页在 LazyVGrid 布局上不起作用,但如果没有 LazyVGrid,分页就可以正常工作。我确实需要将 LazyVGrid 用于我的列表。我该如何解决这个问题?
我的代码
VStack(alignment: .center) {
List {
LazyVGrid(columns: gridItemLayout, spacing: 20) {
ForEach(viewModel.tvShowList, id: \.id) { tvShow in
VStack {
KFImage.url(URL(string: Constant.POSTER_URL + tvShow.posterPath)!)
.placeholder {
Image("placeholder")
.scaledToFill()
.frame(width: 160, height: 100, alignment: .center)
.clipped()
}
.resizable()
.shadow(radius: 10)
.padding(.trailing, 20)
.scaledToFit()
.frame(width: 160, alignment: .center)
Text("\(tvShow.name)")
.multilineTextAlignment(.center)
.lineLimit(1)
.frame(maxWidth: .infinity)
.font(.system(size: 14))
.font(.headline)
}
.listRowBackground(Color.white)
.listRowSeparator(.hidden)
}
.id(UUID())
.frame(maxWidth: .infinity)
if (viewModel.page < viewModel.totalPage) {
HStack {
Spacer()
ProgressView()
.onAppear {
viewModel.page += 1
viewModel.getTvShowTopRated()
}
Spacer()
}
}
}
}
.listStyle(GroupedListStyle())
.padding([.leading, .trailing], 15) }
试试这个, 您需要使用 ScrollView 而不是 List
VStack(alignment: .center) {
ScrollView {
LazyVGrid(columns: gridItemLayout, spacing: 20) {
ForEach(viewModel.tvShowList, id: \.id) { tvShow in
VStack {
KFImage.url(URL(string: Constant.POSTER_URL + tvShow.posterPath)!)
.placeholder {
Image("placeholder")
.scaledToFill()
.frame(width: 160, height: 100, alignment: .center)
.clipped()
}
.resizable()
.shadow(radius: 10)
.padding(.trailing, 20)
.scaledToFit()
.frame(width: 160, alignment: .center)
Text("\(tvShow.name)")
.multilineTextAlignment(.center)
.lineLimit(1)
.frame(maxWidth: .infinity)
.font(.system(size: 14))
.font(.headline)
}
.listRowBackground(Color.white)
.listRowSeparator(.hidden)
}
.id(UUID())
.frame(maxWidth: .infinity)
if (viewModel.page < viewModel.totalPage) {
HStack {
Spacer()
ProgressView()
.onAppear {
viewModel.page += 1
viewModel.getTvShowTopRated()
}
Spacer()
}
}
}
}
.listStyle(GroupedListStyle())
.padding([.leading, .trailing], 15) }
希望有帮助!
在
ScrollView
中滚动太快时,我遇到了类似的问题,正在添加新项目,但视图似乎“跳”到ScrollView
的底部。
布局问题似乎来自于
ScrollView
和 LazyVGrid
在通过分页加载新项目方面的协作方式。
这是一个对我有用的解决方案:
当获取和添加新项目时,有时它们会出现在顶部加载,或者视图意外跳转。
我在
LazyVGrid
的底部添加了一些额外的空间(高度),通过对 ProgressView
应用高度来解决此问题。这确保了 LazyVGrid
和 ScrollView
的底部之间有一个空间。
代码如下:
ScrollView {
VStack {
LazyVGrid(columns: [.init(.flexible()), .init(.flexible())]) {
ForEach(0...5, id: \.self) { _ in
CellItem() // Your custom cell
}
}
ProgressView()
.frame(height: 300) // Adds space
.onAppear {
// Fetch the next page here
}
}
}