Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading