WishIHadThreeGuns
WishIHadThreeGuns

Reputation: 1479

ScrollView in VStack align to bottom in swiftui

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?

Upvotes: 5

Views: 3007

Answers (1)

Adam
Adam

Reputation: 5145

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

Upvotes: 6

Related Questions