Home > Net >  Pin text to bottom of scroll view SwiftUI
Pin text to bottom of scroll view SwiftUI

Time:06-03

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

CodePudding user response:

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)
}

CodePudding user response:

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

  • Related