Search code examples
swiftuiscrollview

SwiftUI offset items in ScrollView under another view


I have a VStack with some content at the top of my app, then a ScrollView on the bottom, with these views being seperated with a Divider. Is there any way to offset the scrollView such that it starts slightly tucked under the Divider and the top view?

Here is an example image of what I want:

enter image description here

The numbers are in a ScrollView and the top content is simply Color.white in this example.

If I apply a simply y offset, though, I get this:

enter image description here

The number is vertically shifted up, but not "tucked" under.

Is there an easy way to get the "tucked" result? I'm sure I could use a ZStack or something, but that seems like a lot of work, especially because I don't know how large the top content will be.

Example Code:

struct ContentView: View {
    var body: some View {
        VStack(spacing: 0) {
            Color.white.frame(height: 100)
        
            Divider()
        
            ScrollView {
                ForEach(0..<20) { number in
                    Text("\(number)")
                }
            }
            .offset(y: -8)
        }
    }
}

Solution

  • I assume you just need padding for scroll view, like

    enter image description here

    ScrollView {
        ForEach(0..<20) { number in
            Text("\(number)")
        }
    }
    .padding(.top, -8)   // << here !!
    .clipped()