Search code examples
swiftuiswiftui-form

Why does the SwiftUI "Form" cause my button to go to the bottom of the screen?


I want to create a view that has a form with a button below it. If I include a form and a button, the button goes to the bottom of the screen.

Without Form Element enter image description here

With Form Element enter image description here

Is this just a SwiftUI bug? Or am I doing something wrong?

//
//  TestFile.swift
//  searchparty
//
//  Created by Me
//

import SwiftUI

struct TestFile: View {
    var body: some View {
        VStack {
            Form{
                Text("Hello, World!")
            }
            
            Button("Button") {
                print("Button tapped!")
            }
        }
    }
}

struct TestFile_Previews: PreviewProvider {
    static var previews: some View {
        TestFile()
    }
}

Solution

  • An empty Section with a footer will do the job, although you'll want to explicitly set the font, or else the footer will change it based on the form footer environment:

    struct ContentView: View {
        var body: some View {
            Form {
                Text("Entry")
                
                Section(footer:
                            HStack {
                                Spacer()
                                Button(action: {}) {
                                    Text("My button")
                                        .font(.system(.body))
                                }
                                Spacer()
                            }
                ) {
                    EmptyView()
                }
            }
        }
    }