我试图实现一个包含三种不同数据类型的选项卡布局LazyVGrid.为此,我使用了一个scrollView并创建了多个LazyVGrid来容纳这些数据.
我面临的问题是,每当滚动选项卡1中的列表时,该选项卡中的列表都会以相同的偏移量滚动.
我已经try 过两种不同的解决方案-
- 将LazyVGrid创建为一个变量-我无法做到这一点,因为它将拥有的数据属于ViewModel,并且LazyVGrid在一个实际示例中是一个单独的视图.
- 每次都使用ScrollView-我try 过这样做,但每次当前 Select 的类型更改时,SwiftUI都会强制LazyVGrid重新填充并从偏移量0显示.
下面是我的代码,如果有人能帮助我认识到如何解决这个问题,那就太好了.
请找到我的代码和电流输出.我希望当我切换选项卡并返回时,ScrollView偏移保持在我离开它的位置.
import SwiftUI
enum SearchType: String, CaseIterable {
case movie = "Movies"
case tv = "TV Shows"
case people = "People"
}
struct SearchContainerView: View {
@ObservedObject var viewModel = SearchViewModel()
@State var currentSelectedSearchType: SearchType = .movie
let array: [String] = ["The", "above", "works", "great", "when", "you", "know", "where", "in", "the", "array", "the", "value" ,"is", "that", "is", "when" ,"you", "know", "its", "index", "value", "As", "the", "index", "values", "begin", "at" ,"0", "the" ,"second", "entry", "will", "be", "at", "index", "1"]
var body: some View {
NavigationView {
VStack {
HStack {
ForEach(SearchType.allCases, id: \.self) { type in
HStack {
Spacer()
Text(type.rawValue)
.font(.title3)
.onTapGesture {
self.currentSelectedSearchType = type
}
Spacer()
}
.padding(5)
.background(currentSelectedSearchType == type ? Color.gray : Color.clear)
.cornerRadius(10)
}
.background(Color.gray.opacity(0.5))
.cornerRadius(10)
.padding(.horizontal)
}
ScrollView {
switch currentSelectedSearchType {
case .movie:
LazyVGrid(columns: [
GridItem(.flexible()),
GridItem(.flexible()),
GridItem(.flexible())
], content: {
ForEach(array, id: \.self) {
Text($0).font(.largeTitle).bold().frame(width: UIScreen.main.bounds.width / 3, height: 100, alignment: .center)
}
})
case .tv:
LazyVGrid(columns: [
GridItem(.flexible()),
GridItem(.flexible()),
GridItem(.flexible())
], content: {
ForEach(array, id: \.self) {
Text($0).font(.largeTitle).bold().frame(width: UIScreen.main.bounds.width / 3, height: 100, alignment: .center)
}
})
case .people:
LazyVGrid(columns: [
GridItem(.flexible()),
GridItem(.flexible()),
GridItem(.flexible())
], content: {
ForEach(array, id: \.self) {
Text($0).font(.largeTitle).bold().frame(width: UIScreen.main.bounds.width / 3, height: 100, alignment: .center)
}
})
}
}
}
}
}
}
电流输出-
<img src="https://i.imgur.com/TgkIXYo.mp4" alt="this slowpoke moves" width="250" />