2

How can I pin a view element to the bottom of a scrollview/VStack in SwiftUI? I've tried using spacers but that doesn't seem to be working. I need the 'Footer' text to be at the bottom of the scroll view/Vstack, how can I do that?

struct ContentView: View {
    var body: some View {
        VStack {
            ScrollView(.vertical, showsIndicators: false) {
                VStack(alignment: .leading) {
                    Text("Top Title")
                    Text("Body")
                    Spacer()
                    Text("Footer") // SHOULD BE PINNED TO BOTTOM OF SCROLL VIEW
                        .frame(alignment: .bottom)
                }
            }
            .background(Color.red)

            Button("Done") {
                //some action
            }
        }
    }
}

enter image description here

stackich
  • 3,607
  • 3
  • 17
  • 41
tHatpart
  • 1,302
  • 3
  • 12
  • 27

2 Answers2

5

Here is possible approach:

ScrollView(.vertical, showsIndicators: false) {
    VStack(alignment: .leading) {
        Text("Top Title")
        Text("Body")
    }
}
.overlay(
    Text("Footer") 
, alignment: .bottom)   // << here !!

Guess 2: probably you wanted this

GeometryReader { gp in
    ScrollView(.vertical, showsIndicators: false) {
        VStack(alignment: .leading) {
            Text("Top Title")
            Text("Body")
            Spacer()
            Text("Footer") // SHOULD BE PINNED TO BOTTOM OF SCROLL VIEW
                .frame(alignment: .bottom)
        }
        .frame(maxWidth: .infinity, minHeight: gp.size.height)
    }
    .background(Color.red)
}
Asperi
  • 228,894
  • 20
  • 464
  • 690
1

You are properly looking for the safeAreaInset modifier: https://developer.apple.com/documentation/swiftui/menu/safeareainset(edge:alignment:spacing:content:)-1dqob/

magnuskahr
  • 1,137
  • 9
  • 17
  • A great solution but not available before iOS 15. Asperi's solution works for iOS 14 as well. – bitops Dec 18 '22 at 06:34