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

How to center-align a Textfield in a VStack?

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)

        }
    
    }
}

>Solution :

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

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)
    }
}
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