代码之家  ›  专栏  ›  技术社区  ›  soleil

SwiftUI滚动视图粘性标题,不使用列表

  •  0
  • soleil  · 技术社区  · 4 周前

    我一直在和 GeometryReader .onChange(of: geo.frame(in: .global).minY) 长期以来,我一直试图让这项工作顺利进行,但没有取得很大成功。请考虑以下几点:

    struct TestScreen: View {
        
        var body: some View {
            NavigationStack {
                ScrollView {
                    VStack {
                        Text("View A")
                            .frame(height: 50)
                            .frame(maxWidth: .infinity)
                            .background(.green)
                        Text("View B - Sticky")
                            .frame(height: 50)
                            .frame(maxWidth: .infinity)
                            .background(.blue)
                        ForEach(0..<15) { i in
                            Text("View \(i)")
                                .frame(height: 50)
                                .frame(maxWidth: .infinity)
                                .background(Color.red)
                        }
                    }
                    
                }
                .navigationBarTitleDisplayMode(.inline)
                .toolbarBackground(.clear, for: .navigationBar)
                .toolbar {
                    ToolbarItem(placement: .principal) {
                        Text("Testing")
                            .foregroundColor(.purple)
                    }
                }
            }
        }
    }
    

    目标是当您向上滚动视图时,使视图B保持在顶部(就在导航栏下方),当然,当您向下滚动时,视图B会在滚动视图中占据正常位置。我知道你可以做粘头 List Sections 但这并不符合我的需求,因为请注意,视图B(粘性视图)不一定是滚动视图中的第一个项目。

    还要注意,视图B必须位于VStack中所有其他内容的顶部,以便其他内容在其下方滚动。

    1 回复  |  直到 4 周前
        1
  •  1
  •   malhal Benzy Neez    4 周前

    尝试使用 LazyVStack 带截面和钉头:

    • 第一部分包含视图A,没有标题。
    • 第二部分包含 ForEach 作为其主要内容,视图B作为其标题。
    ScrollView {
        LazyVStack(pinnedViews: .sectionHeaders) {
            Section {
                Text("View A")
                    // ... modifiers as before
            }
            Section {
                ForEach(0..<15) { i in
                    // ... content as before
                }
            } header: {
                Text("View B - Sticky")
                    // ... modifiers as before
            }
        }
    }
    

    Animation