SwiftUI align Text and TextField (macOS)

Hi all,
I need some help
Here a prototype of screen on my macOS application:

struct Screen: View {
    @State private var field1:String = ""
    @State private var field2:String = ""
    @State private var field3:String = ""
    @State private var field4:String = ""
    public var body: some View {
        VStack {
            Text("Title")
                .font(.title2)
                .padding(.bottom,5)
            Spacer()
            HStack {
                VStack(alignment: .trailing) {
                    Text("field 1")
                    Text("field 2")
                    Text("field 3")
                    Text("field 4")
                }
                VStack {
                    TextField("Enter value for field 1", text: $field1)
                    TextField("Enter value for field 2", text: $field2)
                    TextField("Enter value for field 3", text: $field3)
                    TextField("Enter value for field 4", text: $field4)
                }
            }
            Spacer()
            HStack(alignment: .top) {
                Button {
                    // My code
                } label: {
                    Text("Cancel")
                }
                Button {
                    // My Code
                } label: {
                    Text("OK")
                }
                .keyboardShortcut(.defaultAction)
            }
            .padding(.top,5)
        }
        .padding(.top,3)
        .padding([.bottom,.leading,.trailing],10)
        .frame(minWidth: 350, minHeight: 200)
    }
}

preview

I’m looking to find a way to align Text to the right (with .trailing it's ok) and with TextField

Do you have any suggestions?

I think you will need to use a GeometryReader to measure the size of the Text and then communicate that up the view hierarchy using a preference key. TBH, this feels like a little bit of sharp edge in the SwiftUI API, but I don't know a better way.

Here's an example of displaying a scrollable grid of numbers in a table and sizes the cells so that the text doesn't clip. While it doesn't directly answer your question, I think it demonstrates the process of measuring and resizing the cell with a preference key.

Hi! You can do this with a custom alignment guide. Have a look at this article.

3 Likes

Try remodelling your fields as a VStack containing an HStack for each label + field rather than an HStack with two VStacks. This should get you closer to where you want to be.

1 Like