SLE
SLE

Reputation: 407

Vertically align items inside an HStack

So I have an HStack, but I can't seem to get the items to properly align vertically, so I wanted to reach out and see if the community can help me.

So here is the code:

HStack(alignment: .center) {
    Text("Already have an account?")
        .foregroundColor(Color.white)
        .font(Font.custom("Nunito-Medium", size: 16))
        .multilineTextAlignment(.center)
        .lineLimit(1)
    Button(action: {
        // Action
    }) {
        Text("Sign In")
            .font(Font.custom("Nunito-Medium", size: 16))
    }
}
.padding(.bottom, 5)
.opacity(0.9)
.border(.yellow)

That produces this:
enter image description here

As you can see, the text inside the HStack, is not vertically aligned, which is driving me nuts and I can't figure it out using modifiers, so I wanted to reach out and see what would be a great way to get things inside an HStack or even VStack and have them be vertically/horizontally aligned properly?

Upvotes: 1

Views: 473

Answers (2)

Tolga Katas
Tolga Katas

Reputation: 375

Here's another one.

   HStack(alignment: .center) {
       Text("Already have an account?")
           .foregroundColor(Color.white)
           .font(Font.custom("Nunito-Medium", size: 20))
           .multilineTextAlignment(.center)
           .lineLimit(1)
       Button(action: {
           //action
       }) {
           Text("Sign In")
               .font(Font.custom("Nunito-Medium", size: 20))
       }
   }
   .opacity(0.9)
   .padding()
   .border(.yellow)

enter image description here

Upvotes: 1

RelativeJoe
RelativeJoe

Reputation: 5114

In SwiftUI, the order of the modifiers matter. You're setting a bottom padding of 5 then bordering the View. If you think about it, the result you're getting is completely logical.

To remedy the issue, move the padding modifier after the border one:

HStack(alignment: .center) {
    Text("Already have an account?")
        .foregroundColor(Color.white)
        .font(Font.custom("Nunito-Medium", size: 16))
        .multilineTextAlignment(.center)
        .lineLimit(1)
    Button(action: {
        // Action
    }) {
        Text("Sign In")
            .font(Font.custom("Nunito-Medium", size: 16))
    }
}
.opacity(0.9)
.border(.yellow)
.padding(.bottom, 5)

And remember, order always matters.

Upvotes: 1

Related Questions