Home > Software design >  How to center-align a Textfield in a VStack?
How to center-align a Textfield in a VStack?

Time:12-29

I'm trying to port an Android application to iOS. I would like for the textfield to be aligned in the middle. How do I achieve this? Here is the code so far:

var body: some View
{
    GeometryReader
    {
        metrics in
        
        VStack (alignment: .center)
        {
            Text("Lazuli Social")
        .font(.largeTitle)
    .foregroundColor(Color(red: 0.02, green: 0.325, blue: 1.0))
    
            TextField("Username or email", text: $user)
        .textFieldStyle(.roundedBorder)
        .frame(width:  metrics.size.width*0.80)
        .background(Color.orange)

        }
    
    }
}

CodePudding user response:

You can use the alignment of the frame of the VStack. You'll also want to set the maxWidth to infinity so it expands.

struct ContentView: View {
    
    @State private var user = ""
    
    var body: some View
    {
        GeometryReader
        {
            metrics in
            VStack
            {
                Text("Lazuli Social")
                    .font(.largeTitle)
                    .foregroundColor(Color(red: 0.02, green: 0.325, blue: 1.0))
                
                TextField("Username or email", text: $user)
                    .textFieldStyle(.roundedBorder)
                    .frame(width:  metrics.size.width*0.80)
                    .background(Color.orange)
            }
            .frame(maxWidth: .infinity, alignment: .center) //<-- Here
        }
    }
}

In general, you may want to try to avoid using GeometryReader except when you absolutely need a size. For example, here, you may want to try padding instead (albeit it gives a slightly different result -- it'll no longer be 80% of the width all the time).

struct ContentView: View {
    
    @State private var user = ""
    
    var body: some View
    {
        VStack
        {
            Text("Lazuli Social")
                .font(.largeTitle)
                .foregroundColor(Color(red: 0.02, green: 0.325, blue: 1.0))
            TextField("Username or email", text: $user)
                .textFieldStyle(.roundedBorder)
                .background(Color.orange)
                .padding(.horizontal, 20)
        }
        .frame(maxWidth: .infinity, alignment: .center)
    }
}
  • Related