Aligning a Text and TextField inside the Section of a Form

Viewed 1191

Another simple SwiftUI tasks that is causing me more trouble than it should.

I can't figure a way to align the Text and TextField correctly.

None of the HSTack alignment seem to yield acceptable results.


import SwiftUI

struct SignIn: View {
    @State var email: String = ""

    var body: some View {
        VStack {
            Text("Sign In")
                .font(.largeTitle)
            Form {
                Section {
                    HStack {
                        Text("ID")
                        TextField("Email", text: $email)
                    }
                }
            }
        }
    }
}

struct SignIn_Previews: PreviewProvider {
    static var previews: some View {
        SignIn()
    }
}

enter image description here

3 Answers

You mentioned trying different HStack alignments, did you try .firstTextBaseline or .lastTextBaseline? Both of these align the Text and TextField correctly for me. So that line becomes

HStack(alignment: .lastTextBaseline) {

Screenshot of Result

Full code:

import SwiftUI

struct SignIn: View {
    @State var email: String = ""

    var body: some View {
        VStack {
            Text("Sign In")
                .font(.largeTitle)
            Form {
                Section {
                    HStack(alignment: .lastTextBaseline) {
                        Text("ID")
                        TextField("Email", text: $email)
                    }
                }
            }
        }
    }
}

struct SignIn_Previews: PreviewProvider {
    static var previews: some View {
        SignIn()
    }
}

One solution is to use another TextField instead of a Text:

HStack {
    TextField("", text: .constant("ID"))
        .fixedSize()
        .disabled(true)
    TextField("Email", text: $email)
    Spacer()

}

It's kinda ugly though.

I was having this same issue, and the answer is simpler than I thought. I ended up adding the modifier .aspectRatio(.fit) and that fixed it for me.

Hope this helps!

Related