1

I want to center a TextField, which is in a VStack, to the center of the main view / screen. I tried everything I could think of. But no matter what I do SwiftUI is centering the whole VStack and not the one TextField to the center. Maybe one of you know how to save my day. Thanks is advance. Here is my code:

import SwiftUI

struct ContentView: View {
    // MARK: - Private Properties
    
    @State private var input: String = ""
    
    @State private var inputs: [String] = []
    
    // MARK: - Body
    
    var body: some View {
        ZStack(alignment: .bottomTrailing) {
            content()
                .frame(maxHeight: .infinity)
            
            saveButton()
        }
        .frame(maxHeight: .infinity)
        .background(Color.brown)
    }
    
    // MARK: - Views
    
    private func content() -> some View {
        VStack {
            textField()
            subtitle()
            entries()
        }
        .padding(10)
        .background(Color.yellow)
    }
    
    private func textField() -> some View {
        TextField("TextField", text: $input)
            .font(Font.largeTitle)
            .padding(.horizontal, 20)
            .background(Color.red)
    }
    
    private func subtitle() -> some View {
        Text("Text")
            .background(Color.white)
    }
    
    private func entries() -> some View {
        ForEach(inputs, id: \.self) {
            Text($0)
        }
        .background(Color.purple)
    }
    
    private func saveButton() -> some View {
            Button(action: { inputs.append(input); input = "" },
                   label: { Text("Save") })
            .padding()
    }
}

1
  • Sorry. Maybe it was not clear. But I want to center the TextField vertically in the main view. Commented Aug 29, 2022 at 13:29

1 Answer 1

0

A hack I use sometimes to centre things when nothing else is working :)

VStack {
    Spacer()
    your_view()
    Spacer()
}

See if this works for you

private func textField() -> some View {
    VStack {
        Spacer()
        TextField("TextField", text: $input)
            .font(Font.largeTitle)
            .padding(.horizontal, 20)
            .background(Color.red)
        Spacer()
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

No. I want to have the TextField centered vertically in the main view.
@NickSorge I have modified the answer for vertical centring. The logic remains pretty much the same

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.