以下是尝试双粘性标题视图的完整代码示例:
struct ContentView: View {
var body: some View {
ScrollView(showsIndicators: false) {
LazyVStack(spacing: 0, pinnedViews: .sectionHeaders) {
Section {
SecondView()
} header: {
HeaderView()
}
}
}
}
}
struct HeaderView: View {
var body: some View {
Rectangle()
.fill(.green)
.frame(height: 50)
}
}
struct SecondView: View {
var body: some View {
LazyVStack(spacing: 0, pinnedViews: .sectionHeaders) {
Section {
VStack {
ForEach(0..<20) { index in
ItemView(index: index)
}
}
} header: {
SecondHeaderView()
}
}
}
}
struct SecondHeaderView: View {
var body: some View {
Rectangle()
.fill(.red)
.frame(height: 60)
}
}
struct ItemView: View {
let index: Int
var body: some View {
VStack {
Text("Item \(index)")
.padding()
}
.frame(height: 80)
.background(.gray)
}
}
#Preview {
ContentView()
}
请注意,最初,红色的SecondHeaderView
正确位置位于绿色的下方HeaderView
。但是,滚动时,红色标题会滚动到绿色标题下方,直到它停留在与绿色标题相同的 y 位置。
我需要红色标题固定在绿色标题下方。请注意,SecondView
可能并不总是嵌入在中ContentView
。它可以独立存在,但仍然需要自己的单个粘性标题才能工作,因此我认为两个视图都需要LazyVStack
。
我弄乱了各种 GeometryReader 视图偏移,试图让红色标题正确定位,但我无法做到正确。