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

Nick Sorge
  • 21
  • 2

1 Answers1

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()
    }
}
Suyash Medhavi
  • 1,135
  • 6
  • 18