How to create multiple pinned views below each other in SwiftUI?

438 Views Asked by At

I'm trying to create a multiple layered scrollView with each layer being pinned when scrolling through the list. Currently, the pinnedViews are pinned on top of each other when scrolling to the bottom. See screenshots for current and desired behaviour. Current behaviour Desired behaviour

This is the current view structure:

ScrollView {
    LazyVStack(pinnedViews: [.sectionHeaders]) {
        ForEach(data.firstLayeredViews) { firstLayer in
            Section {
                LazyVStack(pinnedViews: [.sectionHeaders]) {
                    ForEach(firstLayer.secondLayeredViews) { secondLayer in
                        Section() {
                            LazyVStack(pinnedViews: [.sectionHeaders]) {
                                ForEach(secondLayer.thirdLayeredViews) { thirdLayer in
                                    Section() {
                                        LazyVStack {
                                            ForEach(thirdLayer.contents) { content in
                                                Text("Content")
                                            }
                                        }
                                     } header: {
                                         GridCellHeader(title: "Layer 3", level: .thirdLayer)
                                     }
                                }
                            }
                        } header: {
                            GridCellHeader(title: "Layer 2", level: .secondLayer)
                        }
                    }
                }
            } header: {
                GridCellHeader(title: "Layer 1", level: .firstLayer)
            }
        }
    }
}

The level parameter of the GridCellHeader determines the leading padding of the Text.

1

There are 1 best solutions below

1
On

This video helped me to figure this out. I need just two nested levels of headers. For a top-level, I used a built-in API LazyVStack(pinnedViews: .sectionHeaders). For a second level, I modified the code from a source and pin it "manually" by calculating frames. I measured FPS, so manual implementation looks good so far. I didn't notice any hitches.