Jacob F
Jacob F

Reputation: 147

Center Elements in HStack

I am trying to implement a text field that is centered, but I cannot seem to do so. I tried doing it in 3 different ways, but it is still leading aligned.

//Mobile Number Field
                    
                    HStack(alignment: .center) {
                        
                        //Enter your number field
                        VStack(alignment: .center, spacing: 6){
                            Text("+ \(loginData.getCountryCode()) \(loginData.phoneNumber)")
                                .foregroundColor(Color.white)
                                .font(Font.custom("URWDIN-Thin", size: 20))
                                .padding(.top, 40)
                                .frame(alignment: .center)
                        }
                        
                        Spacer(minLength: 0)
                        
                    }

So I tried aligning it to center via the HStack and VStack constructors, and also the frame of the text. My result is still this: enter image description here

With the user inputted text being leading aligned as well. Any insight as to how to fix this?

Upvotes: 1

Views: 6025

Answers (2)

Estuardo Recargador
Estuardo Recargador

Reputation: 39

If you're trying to implement a text field you should use TextField… but I suppose than you want to align a Text instead so, implement this: .multilineTextAlignment(.center) on your code.

If you want to explicitly center your Text change your padding parameter with this: .padding(.horizontal, 40).

//Mobile Number Field
                    
                    HStack(alignment: .center) {
                        
                        //Enter your number field
                        VStack(alignment: .center, spacing: 6){
                            Text("+ \(loginData.getCountryCode()) \(loginData.phoneNumber)")
                                .foregroundColor(Color.white)
                                .font(Font.custom("URWDIN-Thin", size: 20))
                                .padding(.horizontal, 40)
                                .multilineTextAlignment(.center)
                        }
                        
                        Spacer(minLength: 0)
                        
                    }

Upvotes: 1

HunterLion
HunterLion

Reputation: 4006

HStack aligns vertically in the center. VStack aligns in the center, but you added it inside an HStack and then pushed your stack to the left with the Spacer().

Just add a Spacer() before the VStack. Or just the following:

HStack {
    Spacer()
    Text("In the center")
    Spacer()
}

Upvotes: 5

Related Questions