5

I can't get this scrollview to align to the bottom in SwiftUI!

I've three items in the scrollview, but I want them to be aligned to the bottom of the screen (the red arrow shows where I WANT the items to be!)

enter image description here

Here is my code:

import SwiftUI

struct ContentView: View {
    var body: some View {
        ZStack {
            Color.blue.edgesIgnoringSafeArea(.all)
            VStack {
                ScrollView {
                    Spacer(minLength: 80)
                    Text("a")
                    Text("b")
                    Text("c")
                }.frame(maxHeight: /*@START_MENU_TOKEN@*/.infinity/*@END_MENU_TOKEN@*/)
                Text("Button")
                    .padding()
            }.frame(alignment: .bottom)
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

I'm trying spacers, and rotating content by 180 degrees? What should I do?

3
  • Does this answer your question stackoverflow.com/a/58708206/12299030? Commented Aug 19, 2021 at 9:02
  • That's really old (outdated API?) + about scrolling Commented Aug 19, 2021 at 9:05
  • 1
    Ok, but vertical ScrollView has no bottom - it grows there by defined-size content, so then it is not clear how do you want it to fill and behave. Commented Aug 19, 2021 at 9:37

1 Answer 1

6

GeometryReader to the rescue! First, wrap the ScrollView in a GeometryReader so you can get the scrolling area’s height. Then set that as the minimum height of the ScrollView’s content and use bottom alignment:

var body: some View {
    ZStack {
        Color.blue.edgesIgnoringSafeArea(.all)
        VStack {
            GeometryReader { geometry in
                ScrollView {
                    VStack {
                        Text("a")
                        Text("b")
                        Text("c")
                    }
                    .frame(maxWidth: .infinity,
                           minHeight: geometry.size.height,
                           alignment: .bottom)
                }
            }
            Text("Button")
                .padding()
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

This works, Life saver! thank you! In my case, I didn't need the VStack outsie of the GeometryReader either.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.