SwiftUI: How to align icon to left side of centered text field?

Viewed 508

I've got a TextField in SwiftUI that is centered on the screen. I want to add a pencil icon immediately. to the left of it to indicate that it is editable - how can I do this? I've tried embedding both the TextField and Image in an HStack like this:

HStack {
  Spacer()
  Image(systemName: "pencil")
  TextField(...)
}

But that only yields something like this: enter image description here where the textfield is no longer centered and the pencil is aligned to the left of the screen.

Any guidance is appreciated.

2 Answers

this should do it:

        TextField("", text: $input)
            .overlay(alignment: .leading) {
                Image(systemName: "pencil")
                    .offset(x: -24, y: 0)
            }
struct CustomTextFieldView: View {
     @State private var text: String = ""
    
     var body: some View {
        VStack(alignment: .leading) {
            textfeild
                .padding()
        }
    }
    var textfeild: some View {
        HStack {
            Image(systemName: "pencil")
            TextField("Edit me!", text: $text)
        }
        .textFieldStyle(DefaultTextFieldStyle())
    }
}

struct CustomTextFieldView_Previews: PreviewProvider {
    static var previews: some View {
        CustomTextFieldView()
    }
}
Related