21

I am experimenting with SwiftUI and just trying to have a button at the bottom. Right now it is centered. Wondering how I could force a view to stick superview's bottom as you would do in AutoLayout.

struct ContentView : View {
    var body: some View {
        VStack {
            Text("Test")
        }
    }
}

Thank you!!!

Benjamin Clanet
  • 1,076
  • 3
  • 10
  • 17

2 Answers2

43

You have to add a Spacer view above the text.

struct ContentView : View {
    var body: some View {
        VStack {
            Spacer() // ←- here
            Text("Test")
        }
    }
}
LinusGeffarth
  • 27,197
  • 29
  • 120
  • 174
1

You can use Scrollview to make your long content to not take header and footer place. Like this code:

struct ContentView : View {
    var body: some View {
        VStack {
            Group { // Let say this is your sticky header 
            }
            ScrollView(.vertical, showsIndicators: false) { 
                // This is your long content wrap in here 
            }
            Group { // And this is your sticky footer 
            }
        }
    }
}
Pengguna
  • 4,636
  • 1
  • 27
  • 32
  • This is not working for me on iOS 14 if ScrollView has TextField and keyboard appears. Bottom Group content move above to keyboard. Please let me know the solution. – Shahbaz Sajjad Sep 23 '20 at 11:31
  • You can trigger .isHidden on the bottom Group when the keyboard appears using delegation or notificationcenter (how to: https://stackoverflow.com/a/52426407/5834822). and isHidden value set to State variable. – Pengguna Sep 24 '20 at 03:33