Search code examples
swiftswiftui

Edge-Justify text and buttons in view


I'm very new to swift and trying to align text and buttons to the left/right edges, or at least have the buttons in a vertical column. Target is a MacOS app.

Like this:

enter image description here

(Even better if the folder names, eg "raw_files" are aligned in column)

I've been searching for hours and tried Forms, LabeledContent, adding .frame(width:alignment) to various places but no luck.

I could get the buttons to align horizontally but the text labels are right justified:

enter image description here

Adding .frame() to the Text item gives an error "Trailing closure passed to parameter of type 'FormStyleConfiguration' that does not accept a closure"

        Form
        {
            LabeledContent 
            {
                Button("Set")
                { }
            } label: {
                Text("Destination Folder: bobo")
                    .frame(alignment: .leading)
            }
            
            LabeledContent
            {
                Button("Reset")
                { }
            } label: {
                Text("Source: <none>")
                    .frame(alignment: .leading)

            }
        }
        .frame(width: 300)

This shouldn't be that hard. Any suggestions on how to do it?

EDIT I

Sorry, my bad on the .left vs .leading. I've changed the code but the text labels are still right justified

enter image description here


Solution

  • Use Grid. Result:

    screenshot roughly matching desired output

    Code:

    import PlaygroundSupport
    import SwiftUI
    
    struct MyView: View {
        var body: some View {
            Grid {
                GridRow {
                    // Note that gridColumnAlignment only needs to be used
                    // on one cell in each column, and applies to all cells
                    // in the same column.
                    Text("Source Folder:")
                        .gridColumnAlignment(.trailing)
                    Text("raw_files")
                        .gridColumnAlignment(.leading)
                    Button("Set") { }
                        .gridColumnAlignment(.center)
                }
                GridRow {
                    Text("Destination Folder:")
                    Text("raw_files")
                    Button("Set") { }
                }
                GridRow {
                    Spacer()
                        .frame(width: 0, height: 0)
                    Spacer()
                        .frame(width: 0, height: 0)
    
                    Button("Run") { }
                        .keyboardShortcut(.defaultAction)
                }
            }
            .padding()
            .border(Color.primary)
            .padding()
        }
    }
    
    PlaygroundPage.current.setLiveView(MyView())